Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preprocessor and subsitution of format string

If I put:

#define SIZE 10

and after:

scanf("%SIZEs", s);

I have a runtime error. The preprocessor should substitute SIZE with 10 before to compile, so this should equal (in my opinion) to write

scanf("%10s", s);

so, where is the mistake?

like image 536
StackUser Avatar asked Oct 31 '25 15:10

StackUser


2 Answers

It is not possible to replace the contents of the string literal by 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;
}
like image 50
BLUEPIXY Avatar answered Nov 03 '25 05:11

BLUEPIXY


In your code, the problem is in

  scanf("%SIZEs", s);

Anything residing between the quotes " " of a format string (string literal, in general) will not get substituted through MACRO substitution.

So, your scanf() remains the same as you're written, after preprocessing, and %S (or, %SIZEs, in whole) being one invalid format specifier, you get into undefined behaviour and hence got the error.

You can try the workaround as

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

This way, SIZE will be outside the quotes and will be considered for substitution in preprocessing stage.

like image 20
Sourav Ghosh Avatar answered Nov 03 '25 05:11

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!