What happens when I use the wrong format specifier?

Just wondering what happens when I use the wrong format specifier in C?

For instance:

x = 'A'; printf("%c\n", x); printf("%d\n", x); x = 65; printf("%c\n", x); printf("%d\n", x); x = 128; printf("%d\n", x); 
0
source share
2 answers

What happens when I use the wrong format specifier in C?

Generally speaking, the behavior is undefined. *

However, recall that printf is a variational function and that arguments for variational functions are subject to default promotions. So, for example, a char advances to int . Therefore, in practice, they will give the same results:

 char x = 'A'; printf("%c\n", x); int y = 'A'; printf("%c\n", y); 

whereas this behavior is undefined:

 long z = 'A'; printf("%c\n", z); 


* See, for example, section 7.19.6.1 p9 of standard C99:

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. Sub>

+11
source

since x is A, the first print of f will print: "A".

The second will print the ascii A value (look for it).

The third will print the ascii character for 65 (I think it is A or a, but its letter).

The fourth prints 65.

The fifth will print 128.

-1
source

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


All Articles