Preprocessor operators # and ##

The question was asked: 7 years 10 months ago   views: 63
0
Asked: 04-10-2011 в 22:36:30

Answers   3

5

# placed before macro argument turns it into a string. For example, the code:

#define QUOTE(a) #a int main() { cout << QUOTE(2 + 2) << " = " << 4 << endl; }

after the preprocessing stage will turn into

int main() { cout << "2 + 2" << " = " << 4 << endl; }

A useful example of using - debug, the ASSERT macro. Example implementation:

#define ASSERT(c) \ if (!c) { \ std::cerr << "Assertion failed in" << __FILE__ \ << "(line " << __LINE__ << ") : "<< #c << std::endl; \ exit(1); \ }

If you tell him about the condition, for example, ASSERT(2 * 2 != 4), it will display something like:

Assertion failed in test.cpp(line 12) : 2 * 2 != 4

and will shut down the program.

## need to peck the macro arguments with the other parts of the macro or to each other. It is used rarely, mostly for code generation. Example from Wikipedia:

#define MYCASE(item,id) \ case id: \ item##_##id = id;\ break switch(x) { MYCASE(widget,23); }

After preprocessing becomes:

switch (x) { case 23: widget_23 = 23; break; }
Answered: 04-10-2011 в 23:08:30
2

In the beginning of the line # means actually the beginning of a preprocessor Directive. In the middle of a Directive that refers to it. The fact is that if the macro is inside the quotes, the replacement is not happening. If we need to make makrothumeo in quotation marks, you can write:

#define macro(a) puts(#a)

Line

macro (text);

will be deployed so

puts ("text");

Two ## will produce when you deploy a concatenation of the actual parameters of the macro:

#define macro(a, b) a##b macro (name, 1)

will unfold in

name1

Cm. K&R Chapter 4.11.2

Answered: 04-10-2011 в 23:11:07
-1

Approximately so.

Preprocessor directives:

#define CONSTANT value //constant definition #include file_name //inclusion in the project file file_name #pragma option //set machine-dependent options(compiler options) #define CONSTANT(paaram1) definition //define a macro #ifdef CONSTANT //includes further code, if the constant is DEFINED #ifndef CONSTANT //includes further cat only if the constant is NOT defined #else //use previous two. Includes or excludes further //code depending on the condition pred. section #endif //end conditionally included/excluded code fragments

Something like this...

UPD: the Operator ## is used very infrequently, so it can not think...

Answered: 04-10-2011 в 22:50:07
He is used rarely because not thinking about it. And we are the operators and not the directives. - 05-10-2011 в 08:23:20
We are talking about USING them! Unless someone can describe a statement without giving examples? What a bullshit... UPD: not just to describe and CLEARLY describe! - 05-10-2011 в 20:40:04