Tuesday, June 10, 2008

What are C++ Preprocessor Operators?

Following preprocessor operators are available in C++ that could be used with the #define directive.
  • # is stringify operator turns the operand into a string. Can be used only in macro replacement text. Macro parameter name must follow this operator.
  • ## is concatentation operator to cat preprocessor tokens. Can be used only in macro replacement text. Must not appear in the beginning or end of replacement text.

Demonstrate the usage of preprocessor operators

#include <iostream>
using namespace std;

#define myprint1(a)    cout << #a << endl
#define myprint2(a,b)  cout << a##b << endl

int main()
{
  myprint1(hello);
  myprint2("hello","world");
  return 0;
}
OUTPUT:-
hello
helloworld

3 comments :

  1. The statement below is giving the error:

    "hello and world does not give a valid preprocessing token"

    #define myprint2(a,b) cout << a##b << endl

    ReplyDelete
  2. no error at all,
    here "hello" and "world" two valid token,
    these are two constant string so code is working properly

    ReplyDelete
  3. No that above declaration is wrong. Following declaration is right

    template inline T SQR2(T a)
    {
    return(a*a);
    }
    otherwise it will give compile time error
    that "Declaration terminated incorrectly"

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top