Hash symbol after define macro? [duplicate]
Asked Answered
G

2

5

What does the '#' symbol do after the second define? And isn't the second line enough? Why the first one?

#define MAKESTRING(n) STRING(n)
#define STRING(n) #n
Glary answered 26/1, 2018 at 15:18 Comment(2)
StringificationDelanos
You probably want to stay away from this in C++.Dragon
W
9

This is stringize operation, it will produce a string literal from macro parameter, e.g. "n". Two lines are required to allow extra expantion of macro parameter, for example:

// prints __LINE__ (not expanded)
std::cout << STRING(__LINE__) << std::endl;
// prints 42 (line number)
std::cout << MAKESTRING(__LINE__) << std::endl;
Wintergreen answered 26/1, 2018 at 15:20 Comment(0)
P
0

Hash symbol takes macro argument into a c-string. For example

#define MAKESTRING(x) #x
printf(MAKESTRING(text));

will print text

And first line is only alternative name for this macro.

Purebred answered 26/1, 2018 at 15:20 Comment(1)
It's not an alternative name: the argument wouldn't be expanded otherwise.Fadil

© 2022 - 2024 — McMap. All rights reserved.