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++ 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++ 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++ 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.  

C++ Pointers To Derived Classes

We know that pointers are used for an object of derived classes, we can also use them for the base objects. The pointer to the base class object is type-compatible (can be used in two ways) with a pointer to the object of the derived class. 

To access the variable of the base class, a base class pointer will be used. So, a pointer is a type of base class, and it can access all, public function and variables of the base class since the pointer is of the base class, this is known as a binding pointer.

What is Pointer?

A pointer is a data type that stores the address of other data types in the original address of the memory location. We must declare a pointer before using it to store any variable address.

The general form of a pointer variable declaration is:-

data-type *variable name;

Example: int *emp;

The pointer of Base Class points to an unsimilar object of the derived class

Hence, To point an object to separate classes a single pointer variable is used.

What are Base Class and Derived Class?

Base Class: A base class is a class in OOP(Object Oriented Programming) from which other classes are derived. The Base class member functions and members are inherited from the Object of the derived class.

Base class member access specifiers derived in all three modes of inheritance in C++ are public, protected, and public.

The class which inherits the base class has all members of a base class as well as can also have some new additional properties. Another name for base class is parent class.

Derived Class:  A class that is created from an existing class. The derived class can have more effectiveness concerning the Base class and can easily access the Base class.

The derived class inherits all members and member functions of a base class. Another name for Derived class is sub-class. It can inherit properties and methods of Base Class. All the code can be reused.

The syntax for creating Derived Class

class ExampleBaseClass{
// members....
// member function 
    }
class DerivedClass : public ExampleBaseClass{
// members....
// member function
    }

Public inheritance

When a class uses public access specifier member to derive from a base, all public members of the base class are accessible as public members of the derived class and all protected members of the base class are accessible as protected members of the derived class.

Figure 1 - Pointer to derived class
Figure 1 – Pointer to derived class

What is Upcasting? 

Upcasting is converting a derived-class reference or pointer to a base class. In other words, upcasting allows us to treat a derived type as though it were its base type.

 It is always allowed for a public inheritance, without an explicit typecast. This is a result of the is-a relationship between the base and derived classes

Although C++ permits a base pointer to point to any object derived from that base, The pointer cannot be directly used to access all the members of the derived class we may have to use another pointer declared as a pointer to the derived type.

A derived class is a class that takes some properties from its base class. A pointer of one class can indeed point to another class, but classes must be a base and derived class, then it is possible.

Variable of the base class can be accessed through a base class pointer will be used. So, a pointer is a type of base class, and it can access all, public function and variables of the base class since the pointer is of the base class, this is known as a binding pointer.

In this pointer base class is owned by the base class but points to the derived class object. Similarly, it works with derived class pointer, values are changed.

Example #1

#include<iostream.h>
class base
{
   public:
      int n1;
      void show()
         {
             cout<<”\nn1 = “<<n1;
         }
};

class derive: public base
{

     public:
       int n2;
       void show()
          { 
              cout<<”\nn1 = “<<n1;
              cout<<”\nn2 = “<<n2; 

          }
};

int main()

{
    
   base b;
   base *bptr; //base pointer
   cout<<”Pointer of base class points to it”;
   bptr=&b; //address of base class
   bptr->n1=23; //access base class via base pointer
   bptr->show();
   derive d;
   cout<<”\n”;
   bptr=&d; //address of derive class
   bptr->n1=63; //access derive class via base pointer
   bptr->show();
   return 0;
  }

Output:

The pointer of the base class points to it
n1 = 23
The pointer of base class points to derive a class
n1=63


C++ Pointers To Objects

To understand the topic of pointers to objects, we need to know what is an object , pointer and class. A class is defined in C++ using keyword class followed by the name of class.

The body of class is defined inside the curly brackets and terminated by a semicolon at the end.

What is object?

Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.

As discussed above when object is created memory is allocated. So how do we declare an object.

How to declare Objects ?

When a class is defined, 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;

How to access data members and access functions ?

The data members and member functions of class can be accessed using the dot(‘.’) operator with the object.

For example if the name of object is obj and you want to access the member function with the name printName() then you will have to write obj.printName() .

Example:

//To demonstrate accessing of data members 
#include <bits/stdc++.h>
using namespace std;
class Example
{
    // Access specifier
    public:
    // Data Members
    string Testname;
    // Member Functions()
    void printname()
    {
       cout << " Testname is: " << Testname;
    }
};
 
int main() {
    // Declare an object of class example
    Example obj1;
 
    // accessing data member
    obj1. testname = "Arjun";
 
    // accessing member function
    obj1.printname();
    return 0;
}

Output:
Testname is: Arjun

Output:

Testname is: Arjun

Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them.

As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined.

Example #2

  #include <iostream>
  using namespace std;
   int main () {
   int  var1;
   char var2[10];
   cout << "Address of var1 variable: ";
   cout << &var1 << endl;
   cout << "Address of var2 variable: ";
   cout << &var2 << endl;
   return 0;
}

Output:

When the above code is compiled and executed, it produces the following result −

Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6

What are Pointers?

pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is –

type *var-name;

Example #3

string *student;

Here, type is the pointer’s base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to assign a variable as a pointer. Following are the valid pointer declaration −

int    *ip;    // pointer to an integer
double *dp;    // pointer to a double
float  *fp;    // pointer to a float
char   *ch     // pointer to character

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

How do we use Pointers in C++?

There are few important operations, which we will do with the pointers very frequently.

  1. We define a pointer variable.
  2. Assign the address of a variable to a pointer. 
  3. Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations .

Example #4

#include <iostream>
using namespace std;
int main () {
   int  var = 20;   // actual variable declaration.
   int  *work;        // pointer variable 
   work = &var;       // store address of var in pointer variable
   cout << "Value of var variable: ";
   cout << var << endl;
// print the address stored in ip pointer variable
   cout << "Address stored in ip variable: ";
   cout << work << endl;
   // access the value at the address available in pointer
   cout << "Value of *work variable: ";
   cout << *work << endl;
return 0;
}
Figure 1 - Using pointers
Figure 1 – Using pointers

When the above code is compiled and executed, it produces result something as follows :-

Output:

Value of var variable: 20
Address stored in work variable: 0xbfc601ac
Value of *work variable: 20

As we seen above example , you can access an object either directly, or by using a pointer to the object. To access an element of an object when using the actual object itself, use the dot operator.

To access a specific element of an object when using a pointer to the object, you must use the arrow operator.

To declare an object pointer, you use the same declaration syntax that you would use for any other pointer type.

When to use ‘This’ Pointer ?

To better understand ‘this’ pointer, it is important to know how objects look at functions and data members of a class.

  1. Each object gets its own copy of the data member.
  2. All-access the same function definition as present in the code segment.

Meaning each object gets its own copy of data members and all objects share a single copy of member functions.

This is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++.

  • It can be used to pass current object as a parameter to another method.
  • It can be used to refer current class instance variable.
  • It can be used to declare indexers.

Then now question is that if only one copy of each member function exists and is used by multiple objects, how are the proper data members are accessed and updated?

The compiler supplies an any suggested pointer along with the names of the functions as ‘this’.
The ‘this’ pointer is passed as a hidden argument to all non-static member function calls and is available as a local variable within the body of all non-static functions. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).

When do we use “this” keyword:

When local variable’s name is same as member’s name.

Example #5

#include<iostream>
using namespace std;
/* local variable is same as a member's name */
class Test
{
private:
   int m;
public:
   void setM (int m)
   {
       // The 'this' pointer is used to retrieve the object's m
       // hidden by the local variable 'm'
       this->m = m;
   }
   void print() { cout << "m = " << m << endl; }
};
  
int main()
{
   Test obj;
   int m = 20;
   obj.setM(m);
   obj.print();
   return 0;
}

Output:

m = 20

Final Notes

In the above example program we can see when an ‘this’ keyword is used for local variable(m) and member name(M)  is same.

We learnt how to use pointer and declare pointers and access member functions. Also now we understand when to use this keyword and advantage of it.



Preprocessor In C++

Understanding c preprocessor includes the source code which is  written by programmers is stored in the file “program.c”. The file that is stored then processed by preprocessors and an expanded source code file is generated as named program.

This expanded file is compiled by the compiler and an object code file is generated as named program .obj. Finally, the linker links this object code file to the object code of the library functions to generate the executable file program.exe. 

The preprocessor is best thought of as a separate program that manipulates the text in each code file. When the preprocessor runs, it scans through the code file (from top to bottom), looking for preprocessor directives.

Figure 1 – Preprocessor in C++

What are C++ preprocessor directives ?

Preprocessor programs provide preprocessors directives which tell the compiler to preprocess the source code before compiling.

  • All these preprocessor directives begin with a ‘#’ (hash) symbol.
  • The ‘#’ symbol indicates that, whatever statement starts with #, is going to the preprocessor program,
  • Preprocessor program will execute this statement.

Examples of some preprocessor directives are: 

  • #include, 
  • #define,
  •  #ifndef  etc.

Remember that # symbol only provides a path that it will go to the preprocessor, and command such as include is processed by preprocessor program. For example, include will include extra code to your program. We can place these preprocessor directives anywhere in our program. 

What are the types of preprocessor directives ?

There are 4 main types of preprocessor directives:

  • Macros
  • File Inclusion
  • Conditional Compilation
  • Other directives

What are macros ?

Macros are a piece of code in a program which is given some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro,

Example #1

include <iostream>
//We define LIMIT values as 5
//macro definition
#define LIMIT 5
int main()
{
    for (int i = 0; i < LIMIT; i++) {
        std::cout << i << "\n";
    }
 
    return 0;
}

In the above program, when the compiler executes the word LIMIT it replaces it with 5. The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion. 

What is file inclusion directives ?

This type of preprocessor directive tells the compiler to include a file in the source code program. There are two types of files which can be included by the user in the program. Header File or Standard files: These files contains definition of pre-defined functions like printf(), scanf() etc. These files must be included for working with these functions. Different function are declared in different header files. For example standard I/O(Input/Output) functions are in ‘iostream’ file whereas functions which perform string operations are in ‘string’ file. 

Syntax:

#include< file_name >

The file_name is the name of file to be included. The ‘<‘ and ‘>’ brackets tells the compiler to look for the file in standard directory.

Example #2

‘Main.cpp’
#include<stdio.h>  
#include <iostream.h>
//We included “Circle.h” file_name
#include "Circle.h"

int main()  
{  
    float r;  
  
    cout << "Enter radius of Circle\n");  
    cin >> r;  
  
    cout << "Area of Circle is\n" << circle_area(r, PI)) endl;  
  
    return 0;  
}  


‘Circle.cpp’
double circle_area(float r, float PI)  
{  
 return( PI * r * r );
}  


‘Circle.h’
#define PI 3.14159265358979323846
double circle_area(float, float);

Output:

Enter radius of Circle
5
Area of Circle is 78.539819

‘Main.c’

This is main C program where we include Circle.h file. By including this file we also include macro definition for PI and also the function to calculate area of circle.

Preprocessor includes all the content of Circle.h into Main.cpp source code before passing the code to the compiler

We have to include Main.cpp, Circle.cpp and Circle.h are all in the same directory/folder.

user defined files:

When a program becomes very large, it is good practice to divide it into smaller files and include whenever needed. These types of files are user defined files. These files can be included as:

#include”filename”.

What is conditional compilation ?

Conditional Compilation directives are type of directives which helps to compile a specific portion of the program or to skip compilation of some specific part of the program based on some conditions. This can be done with the help of two preprocessing commands ‘ifdef‘ and ‘endif‘. 

Syntax:
#ifdef macro_name
    statement1;
    statement2;
    statement3;
    .
    statementN;
#endif

If the macro with name as ‘macroname‘ is defined then the block of statements will execute normally but if it is not defined, the compiler will simply skip this block of statements while executing.

Example #3

#include <stdio.h>
#include <iostream.h>
void main ()
{
    cout << "Condition";
    #if 5<8!=1
     cout << "Works";
     cout << "needed";
    #endif
    cout << "Fine";
}

Output:

Condition Fine

Other Directives

Apart from the above directives there are two more directives which are not commonly used. These are: 

#undef Directive:

The #undef directive is used to undefine an existing macro. This directive works as:

#undef LIMIT

#pragma startup and #pragma exit:

These directives helps us to specify the functions that are needed to run before program startup( before the control passes to main()) and just before program exit (just before the control returns from main()). #pragma startup and #pragma exit doesn’t work in GCC compiler.

Example #4

#include <bits/stdc++.h>
using namespace std;    
void first1();
void second2();
  
#pragma startup first1
#pragma exit second2
  
void first1()
{
    cout << "Inside first1()\n";
}
  
void second2()
{
    cout << "Inside second2()\n";
}
  
int main()
{
    void first1();
    void second2();
    cout << "Inside main()\n";
  
    return 0;
}

Output:

Inside first1()
Inside main()
Inside second2()

Summary

The preprocessor directive of both C and C++ are identical and does the preliminary operations before source files are compiled. Therefore, we can say that they are much faster that the source code and are useful in most cases.

It is often in the hands of C/C++ programmer to chose the procedures to preprocess, based on their need. However, one can assume that speed and efficiency are the reason why we write programs that use C/C++ preprocessor codes.