Preprocessor and Format String Substitution

If I put:

#define SIZE 10

      

and after:

scanf("%SIZEs", s);

      

I have a runtime error. The preprocessor must be replaced SIZE

with 10

before compilation, so it must be (in my opinion) to write

scanf("%10s", s);

      

So where is the mistake?

+3


source to share


3 answers


It is not possible to replace the contents of a string literal with a macro.
For example, it does the following:



#include <stdio.h>

#define S_(x) #x
#define S(x) S_(x)

#define SIZE 10

int main(void){
    char s[SIZE + 1];
    scanf("%" S(SIZE) "s", s);
    puts(s);
    return 0;
}

      

+3


source


In your code, the problem is in

  scanf("%SIZEs", s);

      

Anything between the quotes of the " "

format string (string literal, in general) will not be replaced by the MACRO replacement.

So yours scanf()

stays the same as you, after preprocessing and %S

(or, %SIZEs

in general) being one invalid format specifier, you end up in undefined and hence got an error.



You can try a workaround like

 scanf("%"SIZE"s", s);

      

So it SIZE

will be outside the quotes and will be considered for replacement in the preprocessing stage.

+2


source


If you are using SIZE for formatting only, you can also use:

#define SIZE "10"
scanf("%"SIZE"s", s);

      

+1


source







All Articles