#include<stdio.h>
int main()
{
char a='x';
printf("%c %d",a);
return 0;
}
Output:
x 134513696
What is 134513696?
Garbage. This is due to a programming error: You put only one parameter on the stack (a), but printf takes 2 values from the stack, because of the two percent signs.
If you intended to have both outputs, the character and its ordinal value, you should have written printf("%c %d", a, a);
Suppose you enter into a contract with a mafia boss to buy a shipment of goods for $1000. Then instead you only hand over $500, and that night you go home to find a dead kitten in your bed. What did you expect?! C is the mafia boss and you you broke your contract with him. Be glad it was just a useless number on your terminal and not your computer blowing up.
If the number of format specifiers in printf()
is greater than the number of arguments passed the behaviour is undefined.
For example :
printf("%d %d %d", 1, 2); // UB
printf("%f %d %d"); // UB
However if the arguments are greater in number(than the format specifiers) the extra ones are just evaluated and ignored.
For example :
printf("%d" ,1,2); //fine. Prints 1
printf
uses a variable argument list. It cannot check if the number of arguments in your format string (in your case 2 "%c %d"
) are equivanlent to the number of arguments inside the va_list (you have just one), so it will grab some undefined value. The compiler will not check for you, if the format string is properly formated.
精彩评论