Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringizing operator in C/C++

Tags:

c++

c

gcc

llvm

I am trying to use the stringizing operator #, but I get the error stray ‘#’ in program. Here is how I am using it.

#define STR "SOME_STRING"
#define BM 8
#define NUM_OF_THREADS 8
#define VER_STR (STR #BM #NUM_THREADS)

I expect to get SOME_STRING88 for VER_STR but instead get an error. What mistake am I doing?

like image 924
MetallicPriest Avatar asked Nov 21 '13 11:11

MetallicPriest


People also ask

What is Stringizing operator in C?

Stringizing operator (#) The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.

What is token pasting operator?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.

What ## means in C?

## is Token Pasting Operator. The double-number-sign or "token-pasting" operator (##), which is sometimes called the "merging" operator, is used in both object-like and function-like macros.


1 Answers

You need to turn the numerical constants into a string. However, #BM is an error, since the syntax is only valid for macro parameters. So you need to force en expansion through an intermediate macro. And you may as well have a STRINGIFY macro to do it:

#include <iostream>

#define STRINGIFY_(x) #x
#define STRINGIFY(x) STRINGIFY_(x)

#define STR "SOME_STRING"
#define BM 8
#define S_BM STRINGIFY(BM)
#define NUM_OF_THREADS 8
#define S_NUM_OF_THREADS STRINGIFY(NUM_OF_THREADS)
#define VER_STR STR S_BM S_NUM_OF_THREADS

int main() {
    // your code goes here
    std::cout << VER_STR;
    return 0;
}

You can see the above in action at http://ideone.com/cR1KZP

EDIT

As Magnus Hoff pointed out, you can invoke STRINGIFY directly as well:

#define VER_STR STR STRINGIFY(BM) STRINGIFY(NUM_OF_THREADS)
like image 147
StoryTeller - Unslander Monica Avatar answered Oct 15 '22 04:10

StoryTeller - Unslander Monica