开发者

This C program outputs garbage [closed]

开发者 https://www.devze.com 2023-01-29 12:06 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the h开发者_高级运维elp center. Closed 9 years ago.
#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.

0

精彩评论

暂无评论...
验证码 换一张
取 消