The C Preprocessor in C++ programming language

Work of C preprocessor is to change the file related to source coding. It is also to make inlined code with the help of macros. It also puts off the compilation of code more than one time.
Preprocessor has 3 ways of utilization which are directives, constants, and macros. The first one Directive has commands. These commands inform to preprocessor not to use that section of file. The beginning of directives has # sign.
Header Files
For getting text and placing in the present file, # directive is used. It is written in the start of program.
Constants
We can say:

#define [identifier name] [value]

The “identifier name” is always substituted by value. The arithmetical expression should be in parenthesis like that:

#define PI_PLUS_ONE (3.14 + 1)

In this way, your constants will not be damaged.

x = PI_PLUS_ONE * 4;

If there is no parenthesis, then:

x = 3.14 + 1 * 4;

The answer will multiply 1 with four, which is wrong

#define [identifier name]

It is best for conjunction among the other pack of directives.
Provisional assemblage
There are selections to describe if the preprocessor can erase the code previous to the compilation. It has #else, #if, #ifndef and many more but al of them have #endif at the end.

Remarking Code
Provisional assemblage is helpful to remark a set of code.

#if 0

#endif

Keep away from Counting Files Manifold Times
One major trouble is that header file has used in many other files and due to that it get described many times. Here, preprocessor helps in comprising one file for one time.
“#ifndef” helps to describe the term. It makes sure that code is used one time during the stacking of file.

#ifndef _FILE_NAME_H_
#define _FILE_NAME_H_

#endif // #ifndef _FILE_NAME_H_

You can only write (#define _FILE_NAME_H_) for defining the expression.
Parallel way is used for others for example Null.

#ifndef NULL
#define NULL (void *)0
#endif // #ifndef NULL

The good thing is to make remark that what is the statement which is terminated by #endif.
Macros
Preprocessor has a function of describing macro. One of the benefits of macro is; it does not let any function to be called again. Macros can be described in this way:

#define MACRO_NAME(arg1, arg2, ...) [code to expand to]

Plain addition macro has this format:

#define INCREMENT(y) y++

This is not a simple task. It has number of difficult points to understand. If you think to write:

#define MULT(y, z) y * z

After that,

int a = MULT(4 + 2, 5 + 2);

So, what will be the result?

int a = 4 + 2 * 5 + 2;

The result will not be according to your requirement. So, put the parenthesis:

#define MULT(y, z) (y) * (z)

So, the parenthesis will prevent you from getting any wrong value.

#define ADD_FIVE(b) (b) + 5

int y = ADD_FIVE(3) * 3;

Here, you have to put brackets for getting exact value.

#define ADD_FIVE(b) (ba) + 5)

int y = ADD_FIVE(3) * 3;

Brackets will save you from getting any error.

#define SWAP(a, b)  a ^= b; b ^= a; a ^= b;

int y = 10;
int z = 5;

SWAP(y, z);

if(y < 0)
    SWAP(y, z);

The main aim is to show that all statements must have parenthesis.

#define SWAP(x, y)  {x ^= y; y ^= x; x ^= y;}

What happen when code will be like as:

#define SWAP(x, y)  { x ^= y; y ^= x; x ^= y; }

int x = 11;
int y = 6;
int z = 3;


if(x < 0)
    SWAP(x, y);
else
    SWAP(x, z);

The program will not run due to semicolon.

#define SWAP(a, b)  do { a ^= b; b ^= a; a ^= b; } while ( 0 )

int x = 11;
int y = 6;
int z = 3;


if(x < 0)
    SWAP(x, y);
else
    SWAP(x, z);

Now, the program will run properly.
More Gotchas

So, you have got an idea, why macros are difficult in use? The way of increasing value is also a bad point. They do not change the value. They only print it.

#define MAX(a, b) ((a) < (b) ? (b) : (a))
int a = 5, b = 10;
int c = MAX(a++, b++);

The result will be:

int y = (y++ < z++ ? z++ : y++)

The problem here is that y++ ends up being evaluated twice! The nasty consequence is that after this expression, y will have a value of 12 rather than the expected 11. This can be a real pain to debug!
Various line macros

Now, we will use many lines macro.
For example:

#define SWAP(x, y)  {                   \
                        x ^= y;         \
                        y ^= x;         \
                        x ^= y;         \
                    }

It is not necessary to put slash in the end. Slash shows that macro is go on the new line.
Highly developed Macro actions
A macro can do a lot of functions on arguments. It can change them in strings. It can stick them collectively.
Publishing Tokens
The argument, which goes to the macro is called token. From time to time, arguments get published jointly and make a token. It will create trouble. The good thing is that to put a macro in the structure for printing.

Double # will use for pasting more than one argument.

For example:

#define BUILD_FIELD(field) my_struct.inner_struct.union_a.##field

It will come as:

my_struct.inner_struct.union_a.field1

String-izing Tokens
It is good to twist the token in the string. The format is:

#define PRINT_TOKEN(token) printf(#token " is %d", token)

Developed form:

printf("<foo>" " is %d" <foo>)

It can be used for printing or even get printed itself.

PRINT_TOKEN(a + b);

Template specialization and Partial Template Specialization


Template Specialization

Template specialization is used to supersede the designed template in order to hold a specific type with a changed way.
If many of the vectors are used in the form of arrays then you have to store some space in the memory. You should have 2 different classes of vectors. The 1st class of vector can be shown:

template <typename T>
class vector
{

    private:
    T* vec_data;  
                   
    int length;    
    int vec_size;  
};

All systems need one bit but they mostly use 16 bits or 32 specified for each and every Boolean. If we have to create our own vector then it should be diverse from others. It may have array where we can easily change the bits.
One more thing is that we have to define something like a template. It is important that its parameters must be vacant.

template <>

This is the format of template:

template <>
class vector <bool>
{

    private:
    unsigned int *vector_data;
    int length;
    int size;
};

It is important to know that specialized edition of vector had changed interface as compare to generic class of vector.

You have to avoid the presence of doubles of vector. For this purpose, you have to use template specialization.

If there is a vector which needs well defined operator with a number of classes printed by somebody with having a function that will be used for contrast, then you can make it yours by splitting up the classes.

Template fractional Specialization
It works same like completed specialization. Here, you have to wind up applying the template. It means that the template concentrate on single characteristic and other characteristics will be settled by the user.

Suppose we require pointers for sorted vectors. The objects will be sorted by giving the value.

template <typename T>
class sortedVector
{
    public:
    void insert (T val)
    {
        if ( length == vec_size )         {
            vec_size *= 2;    
            vec_data = new T[vec_size];
        }
        ++length;
       
        int pos;
        for( pos = length; pos > 0 && val > vec_data[pos - 1]; --pos )
        {
            vec_data[pos] = vec_data[pos - 1];
        }
        vec_data[pos] = val;
    }

    private:
    T *vec_data;
    int length;
    int size;
};

It is good to sort the real type object. For this purpose, we have to use a code. It is given here:

for( pos = length; pos > 0 && *val > *vec_data[pos - 1]; --pos )

Our wish is to exercise fractional specialization on the base of pointer or non pointer type.
If you want to create a template which is partially specialized then the code is given below:

template <typename T>
class sortedVector<T *>
{
    public:
    insert( T *val )
    {
        if ( length == vec_size )  
        {
            vec_size *= 2;  
            vec_data = new T[vec_size];
        }
        ++length;        
       
        int pos;
        for( pos = length; pos > 0 && *val > *vec_data[pos - 1]; --pos )
        {
            vec_data[pos] = vec_data[pos - 1];
        }
        vec_data[pos] = val;
    }

    private:
    T** vec_data;
    int length;
    int size;
};

Here T is used for parameter. T* following the very name of class informs compiler that template will be equivalent to any pointer. Be remember “T” can not use as pointer but used as type to point.

If your vector is fixed vector which can permit to save a type and length of vector, then its coding will be as given below:

template <typename T, unsigned length>
class fixedVector { ... };

This format is for the specialization of booleans:

template <unsigned length>
class fixedVector<bool, length> {...}

“T” is not template parameter. It will not be included in the template except the length.
The question is that how can compiler get to know which is the proper specialization. If there are full, fractional specialization and generic type, then compiler checks the best specialization.
In case, if your demand is sortedVector then you can make complete specialization of sorted vector. Here, compiler will select implementation above partial specialization.

Templated Functions in C++ programming languages

In the language C++, we use the classes as well as function of template. But the functions are a bit trouble-free than classes.
Templated function and templated class have same type of syntax.

template <class type> type func_name(type arg1, ...);

If you have to get addition of 2 values then the required function will be like that:

template <class type> type add(type x, type z)
{
    return x + z;
}

It is clear that the function of addition will be used as we use other functions. The reason is that the type we require is also used for argument. So, compiler will easily understand that which the required type is:

int y = add(1, 2);

It will surely assume that the type will be integer. So, we can say that:

int y = add<int>(1, 2);

Here, template is well explained as the type has given parameter of template.
The truth is that this type is not achievable all the time as it can not be easily deducted by the argument. Your template must have many parameters, if you desire the function to do cast over the argument.

template <class type1, class type2> type2 cast(type1 y)
{
    return (type2)y;
}

If you will not define a right type for “type 2” then this function can not be accessible properly. If the restriction of template is well defined then we can get the benefit of inference type. In the case where it is must that 1st is defined and the 2nd is inferred then the required thing is only defining first one then infer the parameter of second.
Here is an example:

template <class rettype, class argtype> rettype cast(argtype y)
{
    return (rettype)y;
}

Each and everything will be specified in the function, in order to get the accurate type.

cast<double>(10);

The question is that why is it not possible in C++ to make use of inference? The inferences make the classes more compound more in the case when there are many versions of constructors.
“Templated Classes” by way of” Templated Functions”
It seems strange but it is possible that template class can have a function which is also a template. Such function will be taking apart the very class function. Here is example for you:

template <class type> class TClass
{
       
    template <class type2> type2 myFunc(type2 arg);
};

Here, templated class has templated function which is known as “myfunc”. The time when you declare this function then it is necessary to declare it for two times.

template <class type>  // use for class…
    template <class type2>  // use for function…
    type2 TClass<type>::myFunc(type2 arg)
    {
        // set of laws
    }

This way is not correct and it will not execute:

// terrible code…
template <class type, class type2> type2 TClass<type>::myFunc(type2 arg)
{
    // ...
}

The reason is that it shows template in the form of a class. It does not show it as function template.

Templates and Templated Classes in C++ programming language

If you want to know the manners of different classes then Templates will help you. They will build more theoretical classes. It is called generic programming. One important thing about template is that the class of template has no need to get side of datatype. On the whole, the attention of template class is much more on recursive ideas as compare to sole datatype. For instance, it will better for you to create a class which can deal with all kinds of datatype in spite of making classes for each and every datatype. It will make the code trouble-free for you.
The format of templated class:

template <class a_type> class a_class {...};

A_type is used for datatype. It is a kind of an identifier which shows one datatype during carrying out of a program. You can get the help of this line, if you have to describe variables related to a class.

a_type a_var;

When programs come to a specific place then a_type characterizes the datatype. On the other hand, a_var is used to show the type.

template<class a_type> void a_class<a_type>::a_function(){...}

An example of templated class is given below:

a_class<int> an_example_class;

Generic class is the real class and a certain instantiation is made for sole datatype. This rule can be remembered with the help of specialization. Specialization shows the observed item of template class.
During noting down the codes, you will feel it very simple to go to theoretical aspect by covering the real. Similary, it will be helpful to us to create a certain class then move to templated class.

class calc
{
  public:
    int multiply(int y, int z);
    int add(int y, int z);
 };
int calc::multiply(int y, int z)
{
  return y*z;
}
int calc::add(int y, int z)
{
  return y+z;
}

Here are questions that how we can get “generic class” which will be suitable for floating numbers as well? The idea is that it is good to use template.

template <class A_Type> class calc
{
  public:
    A_Type multiply(A_Type y, A_Type z);
    A_Type add(A_Type y, A_Type z);
};
template <class A_Type> A_Type calc<A_Type>::multiply(A_Type y,A_Type )
{
  return y*z;
}
template <class A_Type> A_Type calc<A_Type>::add(A_Type y, A_Type z)
{
  return y+z;
}

If you want to realize templated class then imagine it like to eraze the a_type all over the place. The calc is used to make selection from the datatyoe which suits the class.

calc <double> a_calc_class;

Due to the use of templates, the program can become versatile. Even more, it gives you a chance to use this code again.

The C++ programming language Modulus Operator

Modulus operator is used as an integrated method. It deals with the leftovers which we get by doing some numeral division. It is written like “%” this. It is a kind of formula which helps us in writing our mathematical problems. For instance, we have to divide 13 by 4. The result will be 1 as a residue. It is difficult to perform this method in C++. Modulus operator gives us a way to execute this method in programming.

This is one of the main functions of modulus operator. But there are many other important tasks which can be carried out by this operator. Mostly, it serves us in getting a number which is haphazardly generated. It makes that number shorter. You can even get to know through this operator about different numbers, whether they are factor of others or not.

You can get an idea about even or odd nature of a number with the help o modulus operator. It divides the number by two. If the answer is zero, then the number is even. Otherwise, it will be called odd.

#include <iostream>

using namespace std;

int main()
{
    int num;
    cin >> num;
    // calculates the residue
    if ( num % 2 == 0 )
    {
        cout << num << " is even ";
    }

    return 0;
}

The main function is num%2= =0. Here, we will get an even number if it will be completely divided by 2. If no residue is left, then that specific number can be used again for division.
What will be your method of checking a prime number by modulus operator?

Getting Random Values in C and C++ programming language with Rand

In C++, random values have a very useful role. These are easy to realize. Most of the programs need random values. For instance, if a game entails the use of 2 dice movement then you can cont the rolls by getting their random values.
Rand is a function which gives us an int whose value range is from 0 to RAND_MAX. A constant compiler is named as RAND_MAX. The important thing is that it is also inclusive. “stdlib.h” has RAND_MAX, and rand function.
The number which has come from “rand” is always reliant on the start value. It shows that the series of number will not vary after execution.
In order to cope with the problem, srand(seed) is used. It permits the application to identify the start value which is utilized by rand.
This way of randomization will change the value after every execution. Now, the problem is what will be the way of getting a random value?
The best way of getting a new value is system clock. So, function time and time_t are used to get time in the clock of computer.
The time of program and a positive number will give you a perfect value. It is best as no 2 programs can run with the same time span.
Here is program which is written for your help. This program gives out 3 values randomly.

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

int main()
{
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);

cout<< rand() << endl;
cout<< rand() << endl;
cout<< rand() << endl;
return 0;
}

In spite of “rand” function, the programmer would like to get tapered or broader range of values. For the solution of this trouble, user will spell out the series of integer showing the lesser and higher bounds. We can think two numbers first from 0 and the other has higher value.
If x and y are 2 integers. Here, x % y is from 0 and inclusive y-1. So, the “rand()%high +1” will return a value between one and high.
Here is a program for our easiness. Try it and learn the programming.

Header: iostream
Reason: Input/Output stream
Header: stdlib
Reason: For functions rand and srand
Header: time.h
Reason: For function time, and for data type time_t
*/
#include <iostream>
#include <cstdlib>
#include <time.h>
const int LOW = 1;
const int HIGH = 6;

using namespace std;

int main()
{
int first_die, sec_die;
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
first_die = rand() % (HIGH - LOW + 1) + LOW;
sec_die = rand() % (HIGH - LOW + 1) + LOW;
cout<< "Your roll is (" << first_die << ", "
<< sec_die << "}" << endl << endl;
first_die = rand() % (HIGH - LOW + 1) + LOW;
sec_die = rand() % (HIGH - LOW + 1) + LOW;
cout<< "My roll is (" << first_die << ", "
<< sec_die << "}" << endl << endl;
return 0;
}