C Tutorial

C is a programming language developed at AT & T’s Bell Laboratories of the USA in 1972. It was designed and written by Dennis Ritchie and Ken Thompson.

Prerequisite

Absolutely no prior knowledge is required to learn C programming. Each topic has many lessons and examples that you can practice and learn.

The first step in learning C programming is to install a C compiler for practice. Learning programming is all about practice coding. The more you practice, the more you will learn.

C Tutorial Topics

List of C programming lessons given below. Learn in top to bottom order.

Recommended Books

Sometimes it is difficult for a self-learner to master programming without proper guidance. As a learner you are totally confused how to begin learning, it happens to most of us.

Lectures are good, but always forgotten when you are out of classroom or when you have finished watching videos. So, all you need is to slowly understand and absorb the concepts and workout examples of each topic in C programming yourself.

Books are your best friend when you are learning by yourself.

Here we recommend few books to get started with C programming language.

C Storage Classes

Variables point to a memory location that has an address and a value stored. Other than this value, a variable also has a storage class.

The C storage classes decide the characteristics of a variable during the execution of a program – the characteristics are storage location, initial value stored, scope, the lifetime of the variable and linkage.

To understand the storage classes we must first discuss these characteristics.

Storage Location

A variable can be stored in memory or the CPU. A storage class decides the location of the value that gets stored in a variable. During its lifetime, a variable holds two things – an address to the memory location and a value of its declared data type.

Initial Value

Every variable is assigned a value by the user or the system assigns a default value to the variable because any variable that is not initialized, does not occupy a space in the memory.

Scope

The scope of the variable decides which different sections of the program can access the variable. There is many types of scope for a variable – block level scope, function level scope, function prototype level scope and source file level scope.

The lifetime of a Variable

The lifetime of the variable tells a programmer, how long the variable is going to hold its storage space and memory address during the execution of the program. After the lifetime of a variable, all resources should be accessible to other components of a program.

Linkage

The linkage tells us whether a variable is public or private. If the variable is sharable to other blocks or functions then it is public, otherwise, it is private.

There are three types of linkage – no linkage, internal linkage, and external linkage. The linkage is connected to the scope of a variable. The block level scope, function level scope and the function prototype level scope does not share variables. So, there is no linkage.

The file level or program level scope can have internal or external linkage. The use of static keyword means that the file level scope has internal linkage. Variable using extern keyword means that its an external linkage.

Types of C Storage Classes

There are four storage classes

  1. Automatic
  2. Register
  3. Static
  4. External

Automatic Storage Class

The automatic storage class variables are declared using keyword – auto. If you do not declare it as auto or some other C storage classes member, by default it is auto storage class member because all variables are stored in memory. When you create a new create a new auto storage class variable – a default garbage value is assigned automatically.

Syntax:

To declare a variable as a member of automatic storage class use following syntax.

auto int number;
number = 100;

Example Program #1

#include < stdio.h >
int main()
{
    auto int number;
    printf("Number =%d\n", number);
    system("PAUSE");
    return 0;
}

Output #1

Number = 1982438964

Register Storage Class

Variables in this class are declared using the keyword – register. The variable is stored in a register, but that is not guaranteed because the storage space of CPU registers are limited. In case, registers are not available, register storage class variables treated as auto class variables and stored in memory.

The default initial value of the register class is a garbage value. Each time you run the program containing register class variable a new garbage value is assigned automatically.

Since register storage class variables are stored in a register, you cannot expect to use the memory reference operator on them. It will produce errors.

The scope of the register class variable is local to its block and no linkage. Its lifetime is till the block of code is running during program execution.

Syntax:-

To declare a variable as register storage class type use following syntax.

register int demo_num;

Example Program #2

#include <stdio.h>
int main()
{
    register int count;
    short int i;
    count = 0;
    for(i = 0 ;i < 10; i++)
    {
        count+
    }
    printf("count = %d\n",count);
    system("PAUSE");
    return 0;
}

Output #2

count = 10

Static Storage Class

The static variables do not get updated when they are outside of the scope of their block. Normally you declare the static storage class variable only once during its lifetime.

They jump between function to function updating the value of the variable. Static variables are stored in a memory and by default, they get a value of 0, if a user did not initialize the static variable. The scope of the static variable is local to its block, function or function prototype or file level.

The static variable does not get destroyed immediately and they jump from function to function call, depending on how many times the function has been called.

Syntax:-

To declare a variable static using the keyword – static.

static int length;

Example Program #3

#include <stdio.h>
void increment();
int main()
{
   /* function call */
    increment();

   /* function call */
    increment();

   /* function call */
   increment();

   system("PAUSE");
   return 0;
}
void increment()
{
    int length = 0;
    static int width;

    /* static integer automatically initialized to 0 */
    printf(" Current iteration !\n\n");
    length++;
    width++;
    printf("Length = %d\t Width = %d\n\n", length, width);
}

Output #3

   Current iteration !
Length = 1        Width = 1
   Current iteration !
Length = 1        Width = 2
   Current iteration !
Length = 1        Width = 3

External Storage Class

There is another C storage class that connects variables within a C program. The external storage class variables can be used outside of the program or file. They have an external or internal linkage. You must declare these variables using the extern keyword. The external storage class variables are stored in memory.

The scope of external storage class variable is global and it can be used by many blocks, functions or files in a C program. In this way, the lifetime of the external storage class variable is as long as the program is running.

Syntax:-

The external variable has two cases

  1. A global variable without extern keyword.
  2. A global variable with extern keyword.

A Global Variable without extern keyword

If you declare a variable outside of the main, it is external and initialized to 0 by default. These variables cannot be used outside of the current source file.

for example,

int x;
int main()
{
    printf("%d\n", x);
}

will print a value of 0.

A Global Variable with extern Keyword

To create an external storage class variable use the following syntax.

extern int x;

The above will only give an error because it does not do anything in memory.

Example Program #4

"file.c"
#include <stdio.h>
int x;
int main()
{
    int p = x + 30;
    printf("p = %d\n", p);
    system("PAUSE");
    return 0;
}
"file2.c"
#include <stdio.h>
extern int x;
x = 39;

Output #4

p = 69
Press any key to continue . . . _

Summary

A summary of all C storage classes in C programming language with each character is given below.

C Storage Class Summary
Figure 1 – C Storage Class Summary

When to use a Storage Class?

The usage of C storage classes depends on the programmer. If the program has constraints for which a storage class can solve the problem, then you should use a storage class variable.

Here is a list of reasons for using a storage class.

  1. When you want to use a variable that keeps the values intact between functions then use a static variable. This is a case of internal linkage.
  2. Register storage class variables are fast because they directly manipulated by a CPU, so it does not go through the memory fetch cycles. You must use them wisely.
  3. When you have variables that are shared between files in the same program, an external storage class variable is most suitable kind of variable type for this.
  4. There are so many scenarios where a C programming storage class can be useful and solve important programming problems. It helps the programmer build useful and efficient C programs.

References

  • Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,
  • Brian W. Kernighan, Dennis M. Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall.

C Data Types

Data types are a very important concept in programming languages. You can choose the right kind of variable types for your program. The data types depend on the compiler which creates machine codes suitable for 16-bit or 32-bit processors.

Sometimes when the processor has backward compatibility, then a 32-bit processor can run a 16-bit machine code successfully.

Integer Data Types

An integer data type is declared using keyword – int. We will have a separate discussion on keywords so let’s not worry about them right now.

If you think of memory, then think of sequence of bytes with an address called a memory address. A memory address is a hexadecimal value. One byte of information is 8-bit of information.

Integer Data TypesRequired Storage
int2 or 4 bytes
short int2 bytes
long int4 bytes
storage requirement for each integer type

On a 16-bit compiler like turbo C++, the int type has requires two bytes storage and on a 32-bit compiler, storage requirement is 4 bytes.

Short int is always 2 bytes in size and long int is always 4 bytes in size.

Range of the data types

What does it mean to have a range of values? We will explain that in a minute. Machine codes are binary strings made of 0s and 1s. They are instructions or data for processor – opcode and operand.

So, the range of a data type is nothing, but number of possible binary strings that is allowed using the byte storage. In other words, ” How many numbers can you store in binary format using 2 or 4 bytes of memory space ?”

For 16-bit compiler the range is

\begin{aligned}\left(\frac{2^{16} }{2}\right )- 1 = \left(\frac{65536}{2}\right ) - 1 = -32768 \hspace{2px} to\hspace{2px} +32767\end{aligned}

For 32-bit compiler the range is

\begin{aligned}\left (\frac{2^{32} }{2}\right ) - 1 =\left (\frac{4294967296}{2}\right)- 1 = -2147483648 \hspace{2px} to \hspace{2px} +2147483647\end{aligned} 

Unsigned and Signed Integers

If you want all positive values, then declare the int variable as unsigned. An unsigned data type disregards the sign bit, so that all the values are positive starting from 0. The unsigned int for 16-bit compiler.

\begin{aligned}2^{16} - 1 = 65536 - 1 = Range \hspace{2px} from \hspace{2px}0\hspace{2px} to \hspace{2px}65535\end{aligned}

unsigned int for 32-bit compiler

\begin{aligned}2^{32} - 1 = 4294967296 - 1 = Range \hspace{2px} from \hspace{2px} 0 \hspace{2px} to \hspace{2px}4294967295.\end{aligned}

Signed data type has both positive and negative values.

For example,

signed long int;
signed short int;

Character Data Types

The character data type takes 1 byte of storage. The signed char and char are the same.

Unsigned and Signed Characters

signed char ; /* Range from -128 to + 127 */
unsigned char; /* Range from 0 to 255 */

Each character has a number and char cannot take values greater than -128 to +127.

Float and Double Data Types

The float and the double data types take 4 bytes and 8 bytes respectively. The long double take 10 bytes of storage.

Data TypesRequired Storage
float4 bytes
double8 bytes
long double10 bytes
storage required for float and double types

An Example Program

#include <stdio.h>
int main()
{
    char p = 'a';
    int s = 10;
    long int q1 = 1000;
    short int q2 = 223;
    float b1 = 23.55;
    double b2 = 33.5545;
    signed char ch = 'h';
    signed int g1 = -33;
    unsigned char ch1 = 'D';
    unsigned int g2 = 234;
    unsigned long int num = 333234;
    unsigned short int num2 = 2442;
    printf("char = %c\n", p);
    printf("int = %d\n",s);
    printf("long int = %ld\n",q1);
    printf("short int =%d\n",q2);
    printf("float = %f\n",b1);
    printf("double = %f\n",b2);
    printf("signed char= %c\n",ch);
    printf("signed int = %d\n", g1);
    printf("unsigned char = %u\n",ch1);
    printf("unsigned int = %u\n",g2);
    printf("unsigned long int = %u\n",num);
    printf("unsigned short int = %u\n",num2);
    system("PAUSE");
    return 0;
}

Output

char = a
int = 10
long int = 1000
short int =223
float = 23.549999
double = 33.554500
signed char = h
signed int = -33
unsigned char = 68
unsigned int = 234
unsigned long int = 333234
unsigned short int = 2442

References

  • Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.
  • Brian W. Kernighan, Dennis M. Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall.

C Variables And Constants

In a C program, some values do not change and some changes with the execution of the program. A constant never changes throughout the program and the variable changes frequently, hence the name.

Types of Constants

Constants can be classified into different types such as numeric constants and character constants. The following figure depicts the types of constants available with C language.

Types of Constants in C language
Figure 1 – Types of Constants in C language

Numeric Constants and Character Constants

The numeric constants involve numbers such as integers and real numbers with decimal part – floating point number and double numbers are most popular types.

The character types are single character constant enclosed using single quotes and string constants are enclosed in double quotes. You can call string constant as a character array. For example,

/* Character constants */
'c'
'A'
/* String constants */
"Elephant"
"Oranges"

Named Constants

Some constant can be named in C programs. This is achieved with the help of C preprocessor commands. The C preprocessor will turn these constants in to values before execution of a program.

#define MAX 100

The command is #define and the name of the constant is MAX with a value of 100.

Rules to Construct Constants and Variables

There are rules to construct constants and variables.

Rules for Constants

You can use a constant directly into an expression in C programs. C programming language will allow only specific operation of a type constant.

For example, you can perform arithmetic operations on numbers, but not on characters.

Rules for Variables

There are important rules to remember before you create a variable. These rules are listed below.

Rule 1: Variable names always start with an underscore or a character.

Rule 2: No other special character allowed in variable names except an underscore.

Rule 3: No white space or a comma allowed in a variable name.

Rule 4: Variable name length depends on the compiler.

This is not a rule, but a best practice – always use meaningful variable names in your program.

Syntax for Constants and Variables

There is no specific syntax for a constant, you can use them directly in your programs.

For example,

A = 10 + 30;
printf ( "%d\n", 100 + 30);

Every variable must be declared and initialized before you use it in a C program. The syntax to declare a variable requires

  • the type of data for the variable
  • a user-defined name for the variable.

For example,

int number;
char grade;

For example,

number = 100;
grade = 'A';

You can initialize a variable at the time of declaration itself.

For example,

int number = 200;
char key = 'B';

Note:- Every statement in C programming language must end with a semi-colon;

Example Program

#include <stdio.h>;
int main() {
    int number;
    float sum;
/* Variable Declaration with data type */
    sum = 0.0;
    number = 1000;
/* Variable initialization for sum and number */
    printf(" %d\n", number);
/* Printing output to console */
    printf(" %d\n", 10.23 + 3.7);
    system("PAUSE");
    return 0;
}

Output

The output of the above example program is given below.

1000
-171798692

References

  • Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.
  • Brian W. Kernighan, Dennis M. Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall.
  • Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.

C++ Program Structure

C++ is a very popular programming language. Every C++ program has a general structure that it must follow.

Here is common structure of a C++ program.

C++ Program Structure
C++ Program Structure

Header Section

The header section is used for

  1. Including header files
  2. Declaring global variables
  3. Declaring functions
  4. Defining constants

You can divide C++ functions into two categories – Builtin functions and User-defined functions. Builtin functions are written in a header file that ends with a .h extension. In other words, builtin functions comes with the C++ compiler located in a directory called Include.

User-defined functions are written by programmers. You can write your own codes and store them in the source file for C++ that ends with extension (.cpp).

Syntax to include header file in a C++ program

#include "iostream.h" 

or 

#include <iostream.h>

When you use double quotes the compiler look for the header file in the directory where the C++ program located and then look for file in Include directory that contains all the headers. Otherwise, if we use < ….> , then compiler look for the file only under Include directory.

The header section is a global section because it is outside the main program. You can declare functions (user-defined) with global scope so that all other functions can call it anytime.

void add() ;

int calculate();

You can declare global variables which is used by the main program components such as functions and expressions.

int number;

char name;

You can specify a macro or a numeric constant value in the header section. The value of a numeric constant does not change during the execution of a program.

Syntax for declaring numeric constant

#define MAX 10

#define PI  3.14

The Main Function

The main function is where your program gets executed first. The main function has a default return type of integer in C++. It calls other functions while executing.

void main()
{

            statement 1;

            statement 2;

            ...

            ...

            statement n;

}

The two braces – { and } indicate a block of statements and main() like every other function has a block of statements. The block is the entire C++ program and when it has finished execution, returns an integer value.

If you do not want main to return any value, use the keyword void main() to indicate this.

Other Functions

A user-defined function is a function that performs some task for the user in the program. It is different from built-in functions because user has the control to change the function anytime.

The programmer declares the function in the head section or in the main body of a C program. The declared function has definition that defines what the function does. The best practice is to keep the function definition after main() function. But, it is not necessary.

Putting it all together

The following is an example of C++ program structure.

#include <iostream.h>

#define NUM 100

void main()

{

        int x = 20;

        int sum = 0;

        sum = x + NUM;

        cout << sum << endl;

}

Output

120

C++ Private Member Function & Nested Functions

You have learnt about member functions earlier. We now expand the idea and talk about private member function and nesting of function in C++.

A function declared inside the class’s private section is known as the “private member function”. A private member function is accessible through the only public member function.

Data Members

Data members include members that are mentioned with any of the fundamental types, as well as other types, including pointer, reference, array types, bit fields, and user-defined types.

You can declare a data member the same way as a variable, except those explicit initializers are not allowed inside the class definition. However, a constant static data member of integral or enumeration type may have an explicit initializer.

If an array is declared as a non-static class member, you must specify all of the dimensions of the array.

A class can have members that are of a class type or are pointers or references to a class type. Members that are of a class type must be of a class type that has been mentioned earlier.

An insufficient class type can be used in a member declaration as long as the size of the class is not needed. For example, a member can be implemented that is a pointer to an insufficient class type.

A class X cannot have a member that is of type X, but it can contain pointers to X, references to X, and static objects of X. Member functions of X can take arguments of type X and have a return type of X. 

Member Functions

Member functions are operators and functions that are initialized as members of a class. Member functions do not include operators and functions initialized with the friend specifier.

These are called friends of a class. You can declare a member function as static; this is called a static member function. A member function that is not initialized as static is called a non-static member function.

The definition of a member function is within the scope of its enclosing class. The body of a member function is explored after the class declaration so that members of that class can be used in the member function body, even if the member function definition appears before the declaration of that member in the class member list.

 When the function mul() is called in the following example, the data variables a, b, and c can be used in the body of mul().

Example #1

class x
{
public:
      int mul()             // inline member function mul
      {return a*b*c;};
private:
      int a,b,c;
};

Nesting of member Functions

Whenever we call a member function inside another member function of one class by using dot operator it is known as Nesting of the member function.

 Normally, the member function which is called by another member function is kept private so that it cannot be called directly using the dot operator.

Example #2

#include<iostream.h>
//nested member function

class squarenumb
{
int number;
public:
long square();
void getnumber();
void display();
};

void squarenumb:getnumber()
{
cout<<"Please enter an integer number:";
cin>>number;
}

long squarenumber::square()
{
number=number*number;
return (number);
}

void squarenumb::display()
{
cout<<"Square of the number:"<<square();

}

int main ()
{
squarenumb square;
square.getnumber();
square.display();

return 0;
}

Output:

Please enter an integer number:10
10
Square of the number:100

Summary

The private member function is protection of data wherever necessary, it is for the data protection. Unlike public functions the restricted access ensure that only required members can access the data, which may happen with nested functions.



C++ Objects As Function Arguments

An object can be passed to a function just like we pass a structure to a function. we can pass the object of another class to a function of a different class. We can pass class objects as arguments and return them from a function.

When we want to initialize all data members of an object with another object, we can pass objects and assign the values of a supplied object to the current object. For complex or large projects, we need to use objects as an argument or parameters. So, here’s the question.  

What is an object?

An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is expressed it means an object is created and memory is allocated. 

Declaring Objects: When a class is initialized, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.

Syntax:

ClassName ObjectName;

What is a class?

A class is a template similar to a blueprint that binds the properties and functions of an entity. You can assign all the entities or objects having similar attributes under a single roof, known as a class. These can further implement the core concepts like encapsulation, data hiding, and abstraction. In C++, a class acts as a data type which can have objects or various instances of the class type. 

  • A Class is a user-defined data type that has data members and member functions.
  • Data members includes data variables and member functions are the functions used to manipulate these variables together these data members and member functions define the properties and behavior of the objects in a Class.

Create a class called “MyCycle”:

class MyCycle {       
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

To create an object of MyCycle, specify the class name, and act in accordance by the object name.

To access the class attributes (myNumb and myString), use the dot syntax (.) on the object:

Example #1

Create an object called “myObj” and access the attributes.

class MyCycle {       
  public:             // Access specifier
    int myNumb;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};
int main() {
  MyCycle myObj;  // Create an object of MyCycle
  // Access attributes and set values
  myObj.myNumb = 15; 
  myObj.myString = "Random Info";
  // Print attribute values
  cout << myObj.myNumb << "\n";
  cout << myObj.myString;
  return 0;
}

Output:

15
Random Info

Passing an Object as an argument

The objects of a class can be passed as arguments to member functions as well as non-members functions either by value or by reference. we can pass class objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required.

 A copy of the actual object is created inside the function when an object is passed by value. This copy is destroyed when the function terminates. Moreover, any changes made to the copy of the object inside the function are not reflected in the actual object.

 On the other hand, only a reference to that object (not the entire object) is passed to the function in a pass-by-reference. Thus, the changes made to the object within the function are also reflected in the actual object. No special keyword or header file is required to do so.

Whenever an object of a class is passed to a member function of the same class, its data members can be accessed inside the function using the object name and the dot operator. However, the data members of the calling object can be directly accessed inside the function without using the object name and the dot operator.

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables.

Syntax: 

function_name(object_name);

Returning Object as argument

The returning object will be stored in another variable Object.

Syntax:

object = return object_name;

Example #2

#include <bits/stdc++.h>
using namespace std;
 
class Test{
public:
    int a;
 
    // This function will take
    // object as arguments and
    // return object
    Test add(Test Ta, Test Tb)
    {
        Test Tc;
        Tc.a = Ta.a + Tb.a;
 
        // returning the object
        return Tc;
    }
};
int main()
{
    Example T1, T2, T3;
 
    // Values are initialized
    // for both objects
    T1.a = 50;
    T2.a = 100;
    T3.a = 0;
 
    cout << "Initial Values \n";
    cout << "Value of object 1: " << T1.a
         << ", \nobject 2: " << T2.a
         << ", \nobject 3: " << T3.a
         << "\n";
 
    // Passing object as an argument
    // to function add()
    T3 = T3.add(T1, T2);
 
    // Changed values after
    // passing object as an argument
    cout << "New values \n";
    cout << "Value of object 1: " << T1.a
         << ", \nobject 2: " << T2.a
         << ", \nobject 3: " << T3.a
         << "\n";
 
    return 0;
}

Output:

Initial Values 
Value of object 1: 50, 
object 2: 100, 
object 3: 0
New values 
Value of object 1: 50, 
object 2: 100, 
object 3: 150

In this example, we can see both the things that are how we can pass the objects as well as return them. When the object T3 calls the add function it passes the other two objects namely T1 & T2 as arguments. Inside the function, another object is declared which calculates the sum of all the three variables and returns it to T3. 


This code and the above code are almost the same, the only difference is that this time the add function returns an object whose value is stored in another object of the same class ‘Test’ T3. Here the value of T1 is displayed by object1, the value of T2 by object2, and the value of T3 by object3.

We can also pass an object as an argument within the member function of the class. This is useful, when we want to initialize all data members of an object with another object, we can pass objects and assign the values of a supplied object to the current object.

For complex or large projects, we need to use objects as an argument or parameters.

Example #3

#include <iostream>
using namespace std;

class Decide
{
	private:
	int a;
public:

	void set(int x)
	{
	a = x;
	}

		void sum(Demo ob1, Demo ob2)
		{
			a  = ob1.a + ob2.a;
		}
		void print()
		{
			cout<<"Value of A :  "<<a<<endl;
		}
};
int main()
{
	//object declarations
	Decide d1;
	Decide d2;
	Decide d3;

	//assigning values to the data member of objects
	d1.set(10); 
	d2.set(20); 

	//passing object d1 and d2
	d3.sum(d1,d2);
	
	//printing the values
	d1.print();
	d2.print();
	d3.print();

	return 0;
}

Output:


Value of A:  10
Value of A:  20
Value of A:  30

How do pass objects to functions?

There are four ways of passing objects to functions. Let’s assume you have a class X and want to pass it to a function.

Pass by value

This creates a shallow local copy of the object in the function scope. Things you modify here won’t be reflected in the object passed to it. For example,

Declaration

void fun(X x);
//Calling
X x;
fun(x);

Pass by reference

This passes a reference to the object to the function. Things you modify here will be reflected in the object passed to it. No copy of the object is created. For example,

Declaration

void fun(X &x);
//Calling
X x;
fun(x);

Pass by const reference

This passes a ‘const’ reference to the object to the function. You cannot modify/reassign the object here directly (you can use its methods that do so though). This is useful if you want the function to have only a read-only copy of the object. No copy of the object is created.

Declaration

void fun(X const &x);
//Calling
X x;
fun(x);

Pass by const pointer

This passes a const pointer to the object to the function. You cannot modify/reassign the pointer here.

This is useful if you want the function to have only the address of this object in the pointer. No copy of the object is created.

Declaration

void fun(X const *x);
//Calling
X x;
fun(&x);

Pass by pointer

This passes a pointer to the object to the function. This is similar to passing a reference to the object. No copy of the object is created.

Declaration


void fun(X *x);
//Calling
X x;
fun(&x);

Summary

You have learned about class and objects, how to treat an object as an argument to a function. Not only that , but you also learnt to return the object once the function terminates. It is quite useful to pass objects through function, instead of individual members. But the overhead to send any large object is high when you duplicate the code.

Therefore, we discussed many methods of passing entire object through function with minimum memory. In future articles, we will explore more on this topic.



C++ File Pointer And File Manipulators

What is a file pointer?

 A pointer is used to handle and keep track of the files being accessed. Every file maintains two pointers called get_pointer (in input mode file) and put_pointer (in output mode file), which tells the current position where reading or writing will take place with the use of opening modes and their respective manipulators.

These pointers help attain random access to the file. Like Moving at once to any area withinside the record rather than shifting through it sequentially.

Functions of file handling:

seekg():-

It is used to move the get pointer to the desired location concerning a reference point.

Syntax: file_pointer.seekg (number of bytes ,Reference point); 	
Example: fin.seekg(10,ios::beg); 

tellg():-

tellg() is used to realize which they get pointer is in a file.

Syntax: file_pointer.tellg(); 
Example: int posn = fin.tellg(); 

seekp():-

seekp() is used to move the put pointer to the desired location concerning a reference point.

Syntax: file_pointer.seekp(number of bytes ,Reference point); 
Example: fout.seekp(10,ios::beg); 

tellp():-

tellp()is used to realize which they get pointer is in a file.

Syntax:     file_pointer.tellp(); 
Example:    int posn=fout.tellp(); 

What are the reference points available?

The reference points are:

ios::beg – These are used from the beginning of the file

ios::end – These are used from the end of the file

ios::cur – These are used from the current position in the file.

Files Usage

  • Data Preservation: Storing files in documents allows to hold records even though this system terminates.
  • Easy Data Access: Accessing records will become easy whilst there may be a large number of records and it’s far saved with inside the record, then these files may be accessed the use of the C++ commands.
  • Portability: It will become less difficult to switch records from one pc to any other with no changes.

Operations On Files

 Various operations that can be performed on a file are:  

  • Creation of a new file (fopen with attributes as “a”)
  • Opening an existing file (fopen).
  • Reading from file (fscanf or fgets).
  • Writing to a file (fprintf or fputs).
  • Moving to a specific location in a file (fseek, rewind).
  • Closing a file (fclose).

fstream library

Before diving into each sub-topics, let us first learn about the header file we will be using to gain access to the file handling method. In C++, the fstream library is used to handle files, and it is dealt with with the help of three classes known ofstream, ifstream, and fstream.

ofstream:

This class helps create and write the data to the file obtained from the program’s output.

ifstream:

We use this class to read data from files and also known as the input stream.

fstream:

This class is the combination of both ofstream and ifstream. It provides the ability of creating, writing, and reading a file.

To access the following classes, you must include the fstream as a header file like how we declare iostream in the header.

Example #1

1 #include<iostrea
2 #include<fstream>

fstream library

Before diving into each sub-topics, let us first learn about the header file we will be using to gain access to the file handling method. In C++, the fstream library is used to handle files, and it is dealt with with the help of three classes known ofstream, ifstream, and fstream.

ofstream:

This class helps create and write the data to the file obtained from the program’s output.

ifstream:

We use this class to read data from files and also known as the input stream.

fstream:

This class is the combination of both ofstream and ifstream. It provides the ability of creating, writing, and reading a file.

To access the following classes, you must include the fstream as a header file like how we declare iostream in the header.

After including the header file, there comes a question saying do we need to create the file within the program or else do we need to use an existing file. But this isn’t that difficult to answer because, in C++, we get four different methods to handle files

Opening Modes

What are opening modes?

An opening mode is a setting to control how the stream opens the file. An opening mode can be provided as a second parameter to the constructor of a file stream or its open() member function.

In the “std::ios” namespace we get all modes.

  • “r”- This mode specifies it is open for reading.

If the file does not exist, fopen() returns NULL.

  • “rb”– This mode specifies it is open for reading in binary mode.

 If the file does not exist, fopen() returns NULL.

  • “w”– This mode specifies it is Open for writing. If the file exists, its contents are overwritten.

If the file does not exist, it will be created.

  • “wb”- This mode specifies it is Open for writing in binary mode.

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

  • “a” – This mode specifies it is Open for append. Data is added to the end of the file.

If the file does not exist, it will be created.

  • “ab” – This mode specifies it is Open for append in binary mode. Data is delivered to the end of the file.

If the file does not exist, it will be created.

  • “r+” – This mode specifies it is Open for both reading and writing.

 If the file does not exist, fopen() returns NULL.

  • “rb+” – This mode specifies it is Open for both reading and writing in binary mode.

If the file does not exist, fopen() returns NULL.

  • “w+”–  This mode specifies it is Open for both reading and writing.

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

  • “wb+”- This mode specifies it is open for both reading and writing in binary mode.       

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

  • “a+” – This mode specifies it is open for both reading and appending.

If the file does not exist, it will be created.

  • “ab+” – This mode specifies it is Open for both reading and appending in binary mode.

    If the file does not exist, it will be created.

Example #2: For writing files

#include <iostream>
#include <fstream>
using namespace std;
int main() {
	fstream my_exfile;
	my_exfile.open("my_exfile.txt", ios::out);
	if (!my_exfile) {
		cout << "File not created here!";
	}
	else {
		cout << "File got created!";
		my_exfile << "Example01";
		my_exfile.close();
	}
	return 0;
}

Output:

The file got created!

Closing File

The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.

fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Example #3: Reading from a File


#include <iostream>
#include <fstream>
using namespace std;
int main() {
	fstream my_exfile;
	my_exfile.open("my_exfile.txt", ios::in);
	if (!my_exfile) {
		cout << "No such file is present";
	}
	else {
		char ch;

		while (1) {
			my_exfile >> ch;
			if (my_exfile.eof())
				break;

			cout << ch;
		}

	}
	my_exfile.close();
	return 0;
}

Output:

Example01
Here, we got the output value which is stored in “example (a)”

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in the case of binary files.

Writing to a binary file?

To write into a binary file, you need to use the fwrite() function. The functions take four arguments:

address of data to be written on the disk

size of data to be written on the disk

number of such types of data

pointer to the file where you want to write.

Syntax:

fwrite(addressData, sizeData, numbersData, pointerToFile);

Example #4 – Writing a binary file using fwrite()

#include <stdio.h>
#include <stdlib.h>
struct threeDig
{
   int d1, d2, d3;
};
int main()
{
   int n;
   struct threeDig dig;
   FILE *fptr;
   if ((fptr = fopen("C:\\program.bin","wb")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

   for(n = 1; n < 5; ++n)
   {
      num.n1 = n;
      num.n2 = 5*n;
      num.n3 = 5*n + 1;
      fwrite(&num, sizeof(struct threeDig), 1, fptr); 
   }
   fclose(fptr); 
  
   return 0;
}

In this program, we create a new file program.bin in the C drive.

We declare a structure threeNum with three numbers – n1, n2, and n3, and define it in the main function as num.

Now, inside the for loop, we store the value into the file using fwrite().

The first parameter takes the address of num and the second parameter takes the size of the structure threeNum.

Since we’re only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points to the file we’re storing the data.

Finally, we close the file.

Manipulators

What are Manipulators?

Manipulators are helping functions that can modify the input/output stream. It does not mean that we change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction (>>) operators.

Types of Manipulators

There are various types of manipulators:

Manipulators without arguments: The most important manipulators defined by the IOStream library are provided below.

endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream.

ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.

ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string.

flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time.

Example #5

#include <iostream>
#include <istream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
    istringstream str("           Challenging");
    string line;
    // Ignore all the whitespace in string
    // str before the first word.
    getline(str >> std::ws, line);
  
    // you can also write str>>ws
    // After printing the output it will automatically
    // write a new line in the output stream.
    cout << line << endl;
    // without flush, the output will be the same.
    cout << "only an example" << flush;
    // Use of ends Manipulator
    cout << "\nc";
    // NULL character will be added in the Output

    cout << "a" << ends;
    cout << "t" << endl;
  
    return 0;
}

Output:

Challenging
only an example
cat

The header file iomanip provides a set of functions called manipulators which can be used to manipulate the output formats.

 They provide the same features as the ios(Input-output system) member functions and flags. Some manipulators are more convenient to use than their counterparts in the class(Input-output system) ios. such that, two or more manipulators can be used as a chain in one statement as shown below:

cout << manip1 << manip2 << manip3 << item;
cout << manip1 << item1 << manip2 << item2;

File Pointer & their Manipulation

The read operation from a file involves getting a pointer. It points to a specific location in the file and the reading starts from that location.

Then, the get pointer keeps moving forward which lets us read the entire file. Similarly, we can start writing to a location where the put pointer is currently pointing. The get and put are known as file position pointers and these pointers can be manipulated or repositioned to allow random access to the file

Summary

The C++ file handling is an effiecient tool to manage program output and data in files. In more advanced way to handing data is connecting C++ to a database system such as SQL server and manage data in an efficient way.

This articles talk about flat files manipulations, but you may like to try this examples with Microsoft excel program also.



C++ File Stream Classes

File streams are the libraries which are utilized in programming. These use the iostream preferred standard library because it offers cin and cout strategies which are used for analyzing from the input and writing to the output respectively. 

A file is a collection of associated data stored in a particular area on a disk.

The data transfer can take place in bi-directional ways,

1. Data switch between the console unit and the program.

2. Data switch between the program and a disk file.

What are the file stream classes?

A file stream can be described by using the  ifstream, ofstream, and fstream classes that are contained in the header file fstream.

 The class to be used depends upon the purpose whether the write data or read data operation is to be executed on the file.

By Using iostream standard library, for reading from input and writing to output it provides cin and cout methods.

Operations in File Handling:

  • Creating a file: open()
  • Reading data: read()
  • Writing new data: write()
  • Closing a file: close()

To read and write from a file we are using the standard C++ library known as fstream

Fstream: It is used to create files, writes information to files, and read information from files.

This class provides maintenance for both input and output operations on the files at the same time. It inherits all the member functions of the istream and ostream classes via iostream class. when a file is opened in default mode, it also contains the open() function.

Ifstream: It is used to read information from files. This class supports input operations on the files

 It inherits the features get( ), getline( ), read( ), seekg( ) and tellg( ) from istream class. When the file is opened in default mode, it contains open( ) function.

The functions of ifstream class are :

(i) get()

This function is used to read a single character from the file. The get pointer specifies the character which has to be read from the file. 

(ii) getline()

This function reads a line of text which results up with a newline character. It can be called using cin object as regard to,

cin.getline( line, size)

Where the line is a variable that reads a line of text.

Size is many characters to be read getline() function reads the input until it encounters ‘\n’ or size ⎼1 character is read. It is not saved instead it is replaced by the null character.

(iii) read()

This function scans for a block of data of length specified by an argument ‘n’. This function reads data sequentially. So when the Ending of the function is reached before the whole block is read then the buffer will contain the elements read until the End of the function.

General Syntax

istream & read(char*str, size n);

(iv) seekg()

This function is used to shift the input pointer (i.e., get) to the given location. It belongs to ifstream. It is a file manipulator.

(v) tellg()

This function is used to shift the current position of the input pointer. It belongs to the ifstream class.

Ofstream: It is used to create files and write information to the files.

This class helps output operations on the files. It inherits the functions put(), seekp(), tellp() and write() from ostream class. When the file is opened in default mode, it also includes the open() function.

The functions of ofstream class are mentioned below,

(i) put();

This function is used to write a single character to the file. A stream object specifies to which file the character should be written. This individual will be located at the position specified by the put pointer. This function belongs to fstream class.

(ii) seekp()

This function is used to shift the output pointer that is gi ‘\n’ven location. It belongs to the ofstream class. It is likewise a file manipulator.

(iii) tellp()

This function is used with output streams and returns the current “put” position of the pointer in the stream.

It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.

(iv) write()

This function presents a line on the screen. It is used by cout object as follows,

cout.write(line, size)

Where the line is the string to be displayed.

Size is the number of characters to be displayed.

If the size of a string is greater than the line (i.e., text to be displayed) then the write() function stops displaying on encountering a null character but displays beyond the bounds of the line.

File streams are the libraries which are utilized in programming. These use the iostream preferred standard library because it offers cin and cout strategies which are used for analyzing from the input and writing to the output respectively. 

A file is a collection of associated data stored in a particular area on a disk.

The data transfer can take place in bi-directional ways,

1. Data switch between the console unit and the program.

2. Data switch between the program and a disk file.

To read and write from a file we are using the standard C++ library known as fstream

(i) get()

This function is used to read a single character from the file. The get pointer specifies the character which has to be read from the file. 

(ii) getline()

This function reads a line of text which results up with a newline character. It can be called using cin object as regard to,

cin.getline( line, size)

Where the line is a variable that reads a line of text.

Size is many characters to be read getline() function reads the input until it encounters ‘\n’ or size ⎼1 character is read. It is not saved instead it is replaced by the null character.

(iii) read()

This function scans for a block of data of length specified by an argument ‘n’. This function reads data sequentially. So when the Ending of the function is reached before the whole block is read then the buffer will contain the elements read until the End of the function.

General syntax,

istream & read(char*str, size n);

(iv) seekg()

This function is used to shift the input pointer (i.e., get) to the given location. It belongs to ifstream. It is a file manipulator.

(v) tellg()

This function is used to shift the current position of the input pointer. It belongs to the ifstream class.

Ofstream: It is used to create files and write information to the files.

This class helps output operations on the files. It inherits the functions put(), seekp(), tellp() and write() from ostream class. When the file is opened in default mode, it also includes the open() function.

What Are Functions Of ofstream class?

The functions of ofstream class are mentioned below,

(i) put();

This function is used to write a single character to the file. A stream object specifies to which file the character should be written. This individual will be located at the position specified by the put pointer. This function belongs to fstream class.

(ii) seekp()

This function is used to shift the output pointer that is gi ‘\n’ven location. It belongs to the ofstream class. It is likewise a file manipulator.

(iii) tellp()

This function is used with output streams and returns the current “put” position of the pointer in the stream.

It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.

(iv) write()

This function presents a line on the screen. It is used by cout object as follows,

cout.write(line, size)

Where the line is the string to be displayed.

Size is the number of characters to be displayed.

If the size of a string is greater than the line (i.e., text to be displayed) then the write() function stops displaying on encountering a null character but displays beyond the bounds of the line.

FileStream Writing to a File

 Example #1

#include <iostream>  
#include <fstream>  
using namespace std;  
int main () {  
 
ofstream filestream("testout.txt");  
 
if (filestream.is_open())  
 
{  
    filestream << “Example for \n";  
    filestream << "Writing to File\n";  
    filestream.close();  
 
}  
 
else cout <<"File does not open";  
 
return 0;  
}   

Output

The content of a text file testout.txt is set with the data:
Example for 
Writing to File 

The content of a text file testout.txt is set with the data:

Example for 

Opening a  File:

A file must be opened before you can read from it or write to it. Either the ofstream or fstream object may be used to open a file for writing and ifstream object is used to open a file for reading purposes only.

You can combine two or more of these values by ORing them together.

 For example: If you want to open a file in write mode and want to truncate it in case that already exists, the following will be the syntax –

ofstream outfile;

outfile.open("file.dat", ios::out | ios::trunc );

Same as we can open a file for reading and writing purposes as follows 

fstream afile;

afile.open(“file.dat”, ios::out | ios::in );

Closing a File:

When a program terminates it automatically removes all the streams, releases all the allocated memory, and closes all the opened files. But it is always a good practice to close all the opened files before program termination.

Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.

void close();

Example #2 – Closing a File

#include <iostream>  
#include <fstream>  
using namespace std;  
int main () {  
  ofstream myfile;  
  myfile.open ("study.txt");  
  if(myfile.is_open()){  
    cout<<"File opened"<<endl;  
    myfile.close();//file close  
    cout<<"File Closed."<<endl;  
  }  
  else{  
    cout<<"Error in file opening"<<endl;  
  }  
  return 0;  
}

Output:

File opened
File Closed

File Position Pointers

Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg (“seek get”) for istream and seekp (“seek put”) for ostream.

The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream, or ios::end for positioning relative to the end of a stream.

The file-position pointer is an integer value that specifies the location in the file as several bytes from the file’s starting location. Some examples of positioning the “get” file-position pointer.

  • position to the nth byte of fileObject (assumes ios::beg)

fileObject.seekg( n );

  • position n bytes forward in fileObject

fileObject.seekg( n, ios::cur );

  • position n bytes back from end of fileObject

fileObject.seekg( n, ios::end );

  • position at end of fileObject

fileObject.seekg( 0, ios::end );

Example #3

fin.seekg(20, ios::beg);   // go to byte no. 20 from beginning of file 

fin.seekg(-5, ios::cur);   // back up 5 bytes from the current position of 

fin.seekg(0, ios::end);      // goes to the end of the file

fin.seekg(-9, ios::end);   // backup 9 bytes from the end of the file

Summary

The file stream has all the built-in functions to create, manipulate files using C++ programming. The article introduced the capabilities of C++ programming. Therefore, in the next article you can learn about file pointers, file manipulation in more detail.



C++ Virtual Functions

In this article, you are going to learn about an important concept in C++ called the virtual functions and pure virtual functions. However, it is recommended that you learn about basics of pointer, classes and derived classes before reading further.

What is Virtual Function?

 A virtual function is a special type of member function that is declared within a base class and is Overridden by a derived class. When you refer to a derived class object using a pointer or a reference to the base class.

 Its name in the base class and the derived classes remains the same Its definition in these classes is indistinct.

We call a virtual function for that object and execute the derived class version of the function.  The virtual function in the derived class is executed through the pointer of the public base class.

How Virtual Functions are declared?

A virtual function is declared by writing the word virtual before function declaration in the base class. The functions with the same name are declared in the derived classes. The use of the word virtual before function declaration in derived classes is optional.

 Once a function is declared virtual in a base class, it becomes virtual in all derived classes; even when the keyword virtual is not written in its definition in the derived classes.

The different versions of a virtual function have derived classes with it.

 In derived classes, the virtual function is reused. A function that is already used is mentioned to override the base class function.

What is Pure Virtual Function?

 A pure virtual function is a virtual function for which we don’t have a fulfillment, we only declare it.

A pure virtual function is declared by assigning 0 while implementing. The virtual function that is only mentioned but not defined in the base class is called the pure virtual function. 

  • The function is made pure virtual in its previous declaration with the keyword virtual and by adding it with equal to 0.
  • A pure virtual function is usually can be  implemented in a base class and must be implemented in a leaf subclass.

You denote that fact by appending the “= 0” to the declaration:

class Abstract Base
{
       virtual void PureVirtualFunction() = 0;
}

Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:

class Derived: public Abstract Base
{
    virtual void PureVirtualFunction() override { }
}

The pure virtual function tells the compiler that the function is pure. The class that contains the pure virtual function exists only to act as a parent of the derived classes. 

This function is implemented in the derived classes.

The base class that has one or more pure virtual functions is called the Abstract Base Class. These classes are designed as a framework or layout for derived classes. 

An abstract base class cannot be identical, that is an object of its type cannot be defined. A pointer to an abstract base class can be defined. 

The derived class that does not have any pure virtual function is called Concrete Derived Class. The pure virtual function of the abstract. Base Class is used in the Concrete Derived Class. The derived classes have their versions of the virtual functions.

The Abstract Base Class is defined at the top of this hierarchy. The Concrete Derived Classes are derived from the Abstract Base Class. The pure virtual functions are declared in the base class. Each derived class contains its version of these pure virtual functions.

Hence, Inferiority is gained within the hierarchy of the class.

What are the Similarities between virtual and pure virtual function?

  • These are the concepts of run-time polymorphism.
  • The syntax declaration of both the functions remains the same all over the program.
  • These functions cannot be global or static.

Differences between virtual function and pure virtual function?

The virtual function and pure virtual function are concepts of run time polymorphism. The main difference between ‘virtual function’ and ‘pure virtual function’ is that ‘virtual function’ has its definition in the base class and also the inheriting derived classes reuse it. 

The pure virtual function has no definition in the base class, and all the inheriting derived classes have to reuse. However, the virtual function is also called dynamic dispatch and run-time dispatch, due to the function called is specified in the run time following the type of the object used

The virtual function’ has its definition in the base class. A ‘Pure Virtual Function’ has no definition in the base class.

A virtual function is created by declaring the function in the base class and adding the keyword ‘virtual’. 

Virtual functions are defined in the base class and overridden in the derived class. Pure Virtual Function is a base class particularly not defined in the base class.

Example of Virtual Function:

#include<iostream.h>
Class bb
{
   Public:
   Virtual void PPP()
   {
   Cout<<” it is the base class ”<<endl;
}
};

Class d1: public bb
{ 
Public:
Void PPP()
{
Cout<<” first derived class”<<endl;
}
};
Class d2: public bb
{
Public:
Void PPP()
{
Cout<<” second derived class”<<endl;
}
};
Main()
{
bb *p;
d1 a;
d2 b;
p=&a;
p->ppp();
p= &b;
p->ppp();
 }

Output:

first derived class
second derived class   

 Explanation of the above program:

In the above program, the keyword “virtual appears only in the definition of the base class bb: it has not been repeated in the derived classes dl & d2 that are derived from the base class bb. Each derived class d1 and d2 and the base class bb have a member function with the same name. i.e. PPP.

The statement “p = &a;“ assigns the address of object bb to the pointer object “p”. When the statement “p->ppp(); is executed for the first time, the pointer object of the base class contains the address of the object of the derived class d1 and the virtual member function of the derived class dl is executed.

Similarly, when the “p->pppo);” statement is executed for the

the second time, the pointer object ‘p’ of the base class contains the address of the derived class d2 and thus the virtual member function of the derived class d2 is executed

in executing the virtual function in c++, the computer selects the function to be called based on the contents of the pointer and not based on the type of the pointer.

Example of Pure Virtual Function:

#include<iostream>
using namespace std;
class B {
  public:
    virtual void s() = 0; // Pure Virtual Function
};

class D:public B {
  public:
    void s() {
     cout << " Example of Virtual Function in Derived class\n";
    }
};
int main() {
  B *b;
  D dobj; // An object of class D
  b = &dobj;// A pointer of type B* pointing to dobj
  b->s();// prints"D::s() called"
}

Output:

Example of Virtual Function in Derived class.