Unexpected output of printf

前端 未结 4 2062
有刺的猬
有刺的猬 2020-11-30 15:15
int a=5;
float b=3.5;
printf(\"%d\",b);
printf(\"\\n%f\",a);

Can anyone please tell me why this code is showing unexpected output (garbage\\n3.5)

4条回答
  •  北海茫月
    2020-11-30 16:17

    Format string incorrect error, according to your declarations of a and b:

    printf("%d",b); <-- "b is float"     Wrong!
    printf("\n%f",a); <-- "a is an int"   Wrong! -- Undefined behavior 
    

    should be:

    printf("%f",b);
    printf("\n%d",a);
    

    Q :- Why you getting that output?

    It's due to undefined behavior of your code:

    From INTERNATIONAL STANDARD ©ISO/IEC ISO/IEC 9899:201x

    7.16.1 Variable argument list access macros

    (page 270)

    7.16.1.1 The va_arg macro

    [...] If there is no actual next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases:
    — one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types;
    — one type is pointer to void and the other is a pointer to a character type

提交回复
热议问题