c - "[...] makes pointer from integer without a cast"背后的想法

标签 c

我一直想知道为什么警告 passing argument 1 from of 'foo' makes pointer from integer without a cast 等等只是警告而不是错误。

实际上这些警告几乎都是错误。

有人知道这背后的想法是什么吗?

  • 主要是为了让史前代码能够无错编译吗?
  • 或者只是为了符合标准?那么后者可能需要一些修复。

例子:

int foo(int *bar)
{
  *bar = 42;
}

void bar()
{
  int n = 0;
  foo(n);      // this is obviously an error
  ...
}

最佳答案

根据 6.5.2.2 函数调用,¶ 7:

If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type

6.5.16.1 Simple Assignment中的相关文字是:

Constraints

One of the following shall hold:

  • the left operand has atomic, qualified, or unqualified arithmetic type, and the right has arithmetic type;
  • the left operand has an atomic, qualified, or unqualified version of a structure or union type compatible with the type of the right;
  • the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) one operand is a pointer to an object type, and the other is a pointer to a qualified or unqualified version of void, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • the left operand is an atomic, qualified, or unqualified pointer, and the right is a null pointer constant; or
  • the left operand has type atomic, qualified, or unqualified _Bool, and the right is a pointer.

这些都不允许左操作数作为指针,右操作数作为整数。因此,这样的赋值(以及上面第一个引用的文本,函数调用)是约束违规。这意味着标准要求编译器对其进行“诊断”。然而,除此之外它还做什么取决于编译器。是的,一个错误是非常可取的,但仅仅打印警告是一种低质量的方式来满足像这样“诊断”约束违规的要求。

关于c - "[...] makes pointer from integer without a cast"背后的想法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54769246/

相关文章:

c++ - 如何同时使用并行和串行版本的 MKL?

c - fgets() 的异常行为

c - 指针 - 转换为结构指针 + Malloc

c - 为什么堆栈和堆都会增长?

C读取二进制文件

c - 如何在c中将值从char变量传输到char数组

c - 博耶摩尔算法的实现?

c - 将数据输出到文本文件的问题

c - 如何用k替换小于k的范围的元素?

c - arm-linux-gcc 编译器链接,找不到文件