What is the # for when formatting using %s

淺唱寂寞╮ 提交于 2019-12-07 05:30:10

问题


I came across this example of an assertion and was wondering what the # is for:

#define ASSERT( x ) if ( !( x ) ) { \
    int *p = NULL; \
    DBGPRINTF("Assert failed: [%s]\r\n Halting.", #x); \
    *p=1; \
  } 

回答1:


It is the "stringize" preprocessing operator.

It takes the tokens passed as the argument to the macro parameter x and turns them into a string literal.

#define ASSERT(x) #x

ASSERT(a b c d)
// is replaced by
"a b c d"



回答2:


#x is the stringification directive

#define Stringify(x) #x

means Stringify(abc) will be substituted with "abc"

as in

#define initVarWithItsOwnName(x) const char* p = #x

int main()
{
   initVarWithItsOwnName(Var);
   std::cout << Var; //will print Var
}



回答3:


# is the preprocessor's "stringizing" operator. It turns macro parameters into string literals. If you called ASSERT(foo >= 32) the #x is expanded to "foo >= 32" during evaluation of the macro.




回答4:


It's a preprocessor feature called stringification. It

replaces [the macro parameter] with the literal text of the actual argument, converted to a string constant.




回答5:


# is the stringizing operator defined in Section 6.10.3.2 (C99) and in Section 16.3.2. (C++03)

It converts macro parameters to string literals without expanding the parameter definition.

If the replacement that results is not a valid character string literal, the behavior is undefined. The order of evaluation of # operator is unspecified.

For instance, syntactically, occurrences of the backslash character in string literals are limited to escape sequences.

In the following example:

1        #define  mkstr(x)  #  x
2        char  *p  =  mkstr(a  \  b);  
       /*  "a  \  b"  violates  the  syntax  of  string  literals  */

the result of the # operator need not be "a \ b".




回答6:


It's the stringizing operator.

http://msdn.microsoft.com/en-us/library/7e3a913x(v=vs.80).aspx




回答7:


What you see is called stringification. It allows you to convert an argument of a macro into a string literal. You can read more about it here http://gcc.gnu.org/onlinedocs/cpp/Stringification.html.



来源:https://stackoverflow.com/questions/5354594/what-is-the-for-when-formatting-using-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!