【问题标题】:Why does `"%c"` exist in `printf` if `char` is converted to `int`?如果将 `char` 转换为 `int`,为什么 `"%c"` 存在于 `printf` 中?
【发布时间】:2012-01-21 09:09:26
【问题描述】:

在 C 中,您有 printf- 和 scanf 类函数的 "%c""%f" 格式标志。这两个函数都使用可变长度参数...,它总是将floats 转换为doublescharsints

我的问题是,如果发生这种转换,为什么 charfloat 存在单独的标志?为什么不使用与intdouble 相同的标志?

相关问题:
Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

【问题讨论】:

    标签: c printf variadic-functions


    【解决方案1】:

    因为打印出来的方式不同。

    printf("%d \n",100); //prints 100
    printf("%c \n",100); //prints d - the ascii character represented by 100
    

    【讨论】:

    • 哦.. 显然。不过,float 呢?
    • @PaulManta:%f 格式化标志需要 double 参数。
    【解决方案2】:

    因为floatdouble 具有不同的机器表示或大小以及调用约定:许多处理器都有专用于浮点的寄存器,这些寄存器可能用于参数传递。

    并且 C 标准要求 short 参数转换为 intfloat 参数转换为 double

    【讨论】:

    • 请注意,这些转换并非针对所有参数,仅针对函数声明未指定参数类型的参数。
    • @Keith:与这个问题相关的是促销总是应用于可变参数。正如您所说,这是“函数声明未指定参数类型的参数”的子集。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2014-02-07
    • 2013-08-10
    • 2018-02-10
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多