4

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

For example:

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); 
8
  • 23
    Why don't you try it and... C Commented May 31, 2013 at 19:32
  • 5
    Ugh, don't abuse the fact that we can't down-vote comments. :) Commented May 31, 2013 at 19:32
  • 4
    Note that in this specific case,you aren't using a wrong format specifier... Commented May 31, 2013 at 19:35
  • 2
    Without a declaration for x this is impossible to answer. Commented Feb 23, 2016 at 15:47
  • 4
    @MattBall That's rarely the proper answer for a C question. Commented Mar 8, 2016 at 10:04

2 Answers 2

20

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

Generally speaking, undefined behaviour.*

However, recall that printf is a variadic function, and that the arguments to variadic functions undergo the default argument promotions. So for instance, a char is promoted to an int. So in practice, these will both give the same results:

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

whereas this is undefined behaviour:

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


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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, undefined behavior as per C11 7.21.6.1 p9.
By the way, I don't see any wrong formatting specifiers in OPs code assuming x has type int.
-3

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

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

The 3rd one will print the ascii character for 65 (I think this is A or a, but its a letter).

The fourth one will print 65.

The 5th one will print 128.

1 Comment

The behaviour will completely depend on type of x (which is not specified in the question itself).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.