首页 > 解决方案 > 不同的语句导致类型转换不同。c/gcc

问题描述

如果我在语句中添加“double”,那么它将打印 60.00,否则代码将打印 0.0000..

#include <stdio.h>

int main(void)
{
    void foo();// if i add "double" into statement then will printf 60.00
    char c = 60;
    foo(c);
    return 0;
}

void foo(double d)
{
    printf("%f\n", d);//now printf 0.0000
}

标签: cgcc

解决方案


你的代码调用未定义行为,因为调用者不知道 foo 的参数。您的原型说该函数将采用未指定数量的参数。它没有说明这些参数的类型。所以它进行隐式转换int并传递int给 foo。

foo需要双参数。

该怎么办?

在函数调用之前添加函数原型。

void foo(double);

int main(void)
{
    char c = 60;
    foo(c);
    return 0;
}

void foo(double d)
{
    printf("%f\n", d);//now printf 60.0000
}

推荐阅读