c - 使用 float 格式说明符打印 int 变量

标签 c visual-studio gcc floating-point printf

int main()
{
    int a=5;
    float b=7.5;

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

    return 0;
}

当我在 gcc 编译器中编译时输出是

5 7.500000
5 7.500000

但是在visual studio中,输出是

5 7.500000
5 0.000000

我无法理解 gcc 编译器的输出。

最佳答案

printf 原型(prototype)是:

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

C11 (n1570),§ 6.5.2.2 函数调用

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 函数调用

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.

因此,printf 调用不会执行其他参数提升。特别是,a 不会转换为 double。因此,它将导致未定义的行为:printf 将尝试获取具有给定大小 (sizeof(double)) 和给定值的 double内存表示,可能与 int 不同。

C11 (n1570),§ 7.21.6.1 fprintf 函数

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.

此外,您可以查看gcc 生成的ASM 代码以了解发生了什么。

关于c - 使用 float 格式说明符打印 int 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17104102/

相关文章:

android - 从 GetStringUTFChars JNI 得不到结果

c# - Microsoft.SqlServer.Management.Smo 命名空间 - 我需要安装什么来解决它?

c# - Visual Studio 复制本地

c - strstr:使用不同版本的 gcc 时行为不同

c++ - libboost 中的 undefined symbol

gcc - libav 将音频持续时间设为负数

c++ - C/C++ ncurses 卡住

c - 为结构中的双指针分配内存时遇到问题

c - 归并排序和递归

android - 制作 Android 应用程序时在 Visual Studio 中引用错误