Printing int variables with float format specifier

前端 未结 1 1551
梦谈多话
梦谈多话 2021-01-15 19:37
int main()
{
    int a=5;
    float b=7.5;

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

    return 0;
}

when i compile this in gcc

1条回答
  •  孤城傲影
    2021-01-15 19:56

    printf prototype is:

    int printf(const char *format, ...);
    

    C11 (n1570), § 6.5.2.2 Function calls

    The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.

    C11 (n1570), § 6.5.2.2 Function calls

    the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions.

    Therefore, no other argument promotion is performed with a printf call. In particular, a is not converted to double. Hence it will result in a undefined behavior: printf will try to get a double with a given size (sizeof(double)) and a given memory representation, which could be different from an int.

    C11 (n1570), § 7.21.6.1 The fprintf function

    If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

    Besides, you can look at the ASM code generated by gcc to see what is going on.

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