【问题标题】:Why i am not getting expected output while passing char to a function in C为什么在将 char 传递给 C 中的函数时我没有得到预期的输出
【发布时间】:2016-04-21 17:00:42
【问题描述】:

这是我写的代码

#include<stdio.h>

main( )
{
    float a = 15.5 ;
    char ch = 'd' ;
    printit ( a, ch );
}
printit ( a, ch )
{
    printf ( "\n%f  %c ", a, ch ) ;
}

输出是:

15.500000 ─

在这里,我希望打印字符 d 来代替 -

【问题讨论】:

  • 1) 正确格式化您的代码。 2) 对于printit 的缺失声明(又名原型),您应该已经收到警告。这也是史前 C(又名 K&R-C)。 永远不要使用它。它已经过时了,因为 ca。 27年。并且代码会调用未定义的行为。
  • 永远不要这样写C代码..除了未定义行为的问题外,这段代码真的很难理解。
  • 你在使用之前没有printit原型/声明。注意你的缩进

标签: c char function-call


【解决方案1】:

TL;DR,您的代码调用undefined behavior

您正在使用一种危险的(谢天谢地,现在是非标准的Ref)方式来获取变量类型,即类型默认为int

由于您的变量缺少数据类型定义,它们默认为int。所以,在printtit()ach 内部是int 类型。

现在,通过将a 作为%f 的参数传递,您已经调用了UB。该程序(及其输出)既不能被信任,也不能以任何方式被证明是合理的。

注意:启用编译器警告并注意它们!


参考:引用自C11(也可在C99 中获得),

第二版的主要改动包括:

。 . . .

——删除隐式int

【讨论】:

    【解决方案2】:

    虽然问题已经解决,但我想添加一个正确重写的代码版本:

    #include<stdio.h>
    
    void printit (float, char); // function declaration
    
    int main(void)
    {
        float a = 15.5 ;
        char ch = 'd' ;
        printit (a, ch);
        return (0);
    }
    void printit (float a, char ch)
    {
        printf("\n%f  %c ", a, ch) ;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      相关资源
      最近更新 更多