The output of the following C code is TT, why not tt?

The output is the following C TT code, but I think it should be TT .

 #include<stdio.h> #define T t void main() { char T = 'T'; printf("\n%c\t%c\n",T,t); } 
+5
source share
2 answers

The preprocessor does not replace any text inside quotation marks, whether it be single quotes or double quotes.

So, the character constant 'T' does not change.

From section 6.10.3 Standard C :

9 Form preprocessing directive

 # define identifier replacement-list new-line 

defines an object-like macro that calls each subsequent instance macro name 171) should be replaced by a replacement list of preprocessing tokens that make up the remainder of the directive. Then, the replacement list is rescanned to get more macro names as shown below.

171) Since all symbolic constants and string literals are macro-substitution times, they are preprocessing tokens , not sequences containing identifier-like subsequences (see 5.1.1.2, phase translation), they are never checked for macro names or parameters.

+8
source

TL DR The variable name T must be replaced by MACRO, not by the initializer 'T' .


To develop, #define MACROs cause text replacements and anything inside the quotation marks (either '' or "" ) are not part of the MACRO replacement.

Essentially, try running the preprocessor on your code (example: gcc -E test.c ) and it looks like

  char t = 'T'; printf("\n%c\t%c\n",t,t); 

Run gcc -E main.c -o test.txt && tail -f test.txt and See it online

which is expected to output the value of the variable T , TT .

However, for a hosted environment, the required signature for main() is int main(void) , at least.

+2
source

Source: https://habr.com/ru/post/1261284/


All Articles