问题
#include <stdio.h>
int main() {
int i=10,j=20;
printf("%d%d%d",i,j);
printf("%d",i,j);
return 0;
}
Using the Turbo C compiler, the output is like:
10 10 garbageValue 20
Can someone explain why this is?
回答1:
Which compiler you are using? I tested it on turbo c v2.0 and turbo c++ v 4.5 compilers and the output is
10 20 garbage value
10
This is the actual output you will get as you are using only two variables and three format specifiers. So it will print the values stored in the two variables and print a garbage value.
In the second case you are using only one format specifier and two variables, so in that case it will only print one value stored in the variable and skips the other variable. You might get the above output if you compile it under turbo c 2.0 and turbo c++ 4.5 compilers.
回答2:
The first call to printf()
has one too many format specifiers, resulting in undefined behaviour. In this case a garbage value is printed.
回答3:
printf("%d%d%d",i,j); =>
you are telling printf to print three integer, but you provide just three, so printf prints some garbage from the stack. the other:
printf("%d",i,j);
is supposed to take just one integer, but you are passing two. The C language does not guard against such errors, and what's happen is completely undefined, so to explain how you see exactly these outputs is difficult unless you know your compiler internal, and not so useful since that code is wrong and expected to fail.
回答4:
The behavior is undefined, meaning the language spec doesn't say what happens in this case. It depends entirely on the implementation of the compiler and on your system architecture. Explaining undefined behavior can be occasionally entertaining, often maddening, and pretty much always useless -- so don't worry about it!
回答5:
You've got your format specifiers all mixed up, and I don't think the code you posted is your actual code. On my Visual Studio compiler, I see this:
1020010
Each %d
denotes a place where printf
should insert one of your integer values.
printf("%d%d%d",i,j);
You told printf
to expect three, but you only gave it two. It's possible Turbo C is doing something different with the arguments under the hood, but you still need to match your format specifiers to your arguments:
printf("%d%d",i,j);
来源:https://stackoverflow.com/questions/11054064/wrong-number-of-parameters-to-printf-leads-to-strange-results