String Operator #

This page was translated by a robot.

Prefixing a macro parameter with a single in a parameterized macro definition #means that the macro parameter is not simply replaced with the passed argument, but that the passed code " "is interpreted as a string in double quotes, which is why this operator is also affectionately known as a stringifier or in English called a stringizer .






i: 5
i+1: 6
#include <stdio.h>
#define MESSAGE(x) printf("%s: %d\n", #x, x)

int main(){
  int i = 5;
  MESSAGE(i);
  MESSAGE(i+1);
  return 0;
}

Details

Here are the two lines as the preprocessor translates them:

printf("%s: %d\n", "i", i);
printf("%s: %d\n", "i+1", i+1);
MESSAGE(i);
MESSAGE(i+1);

It should be noted that the character #here represents a macro operator, i.e. a combination of macro operands. In this case it is a unary macro operator that expects an operand on the right. Only macro parameters are explicitly valid as operands in stringification. If you try to use this macro operator elsewhere in the code, the compiler will report an er.

If the operand to be stringified contains double quotation marks, these are automatically embedded by the preprocessor with escape sequences.





"Hello"
#include <stdio.h>
#define STRING(x) #x

int main(){
  printf(STRING("Hello"));
  return 0;
}

Below is the line as the preprocessor translates it:

printf("\"Hello\"");