【问题标题】:Should a function declaration without the type of its parameters compile in ANSI C?没有参数类型的函数声明应该在 ANSI C 中编译吗?
【发布时间】:2022-10-13 17:04:41
【问题描述】:

我正在调查 ANSI C。这应该编译吗? 此代码能否符合更新的标准? (它试过但总是出错)

#include <stdio.h>
#include <stdlib.h>


float declaration();
float prototype(float);


int main(void)
{
    printf("declaration: %f\n", declaration(10));
    printf("prototype: %f\n", prototype(10));

    return 0;
}


float declaration(float x)
{
    return x;
}

float prototype(float x)

{
    return x;
}

我收到与 -ansi -pedantic-errors -pedantic 冲突的类型错误:

gcc.exe -Wall -g -pedantic-errors -pedantic -ansi -save-temps  -c main.c -o main.o
gcc.exe  -o out.exe main.o   
main.c:18:7: error: conflicting types for 'declaration'
   18 | float declaration(float x)
      |       ^~~~~~~~~~~
main.c:19:1: note: an argument type that has a default promotion cannot match an empty parameter name list declaration
   19 | {
      | ^
main.c:5:7: note: previous declaration of 'declaration' was here
    5 | float declaration();
      |       ^~~~~~~~~~~

令我困惑的是,标准说:

6.2.1 标识符的范围... 函数原型是声明其参数类型的函数的声明。

这可能意味着您可以在没有它们的情况下声明一个函数......

谢谢!

【问题讨论】:

  • 如何6.2.1 标识符的范围意味着您可以在不声明参数类型的情况下声明函数?

标签: c gcc compilation ansi-c


【解决方案1】:

这违反了默认参数提升。常量10 是一个整数常量,根据规则,它将被提升为int。但是,定义中的参数类型为float,与int 不兼容。

您可以尝试使用 10.0 作为参数。

【讨论】:

  • 该错误与呼叫站点无关。这是声明和定义之间的冲突。
猜你喜欢
  • 1970-01-01
  • 2013-01-18
  • 2019-10-05
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多