Wrong number of parameters to printf leads to strange results

后端 未结 4 1715
臣服心动
臣服心动 2021-01-27 01:26
#include 

int main() {
   int i=10,j=20;
   printf(\"%d%d%d\",i,j);
   printf(\"%d\",i,j); 
   return 0;
}

Using the Turbo C compiler,

相关标签:
4条回答
  • 2021-01-27 01:44

    The first call to printf() has one too many format specifiers, resulting in undefined behaviour. In this case a garbage value is printed.

    0 讨论(0)
  • 2021-01-27 01:57

    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);
    
    0 讨论(0)
  • 2021-01-27 02:01
    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.

    0 讨论(0)
  • 2021-01-27 02:03

    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!

    0 讨论(0)
提交回复
热议问题