gpt4 book ai didi

c - 为什么这个执行无效指针初始化的程序在 C 中编译得很好?

转载 作者:太空狗 更新时间:2023-10-29 15:52:13 24 4
gpt4 key购买 nike

我写了一个简单的 C 程序,我原以为它会编译失败,但不幸的是它在 C 中编译并运行良好,但在 C++ 中编译失败。考虑以下程序:

#include <stdio.h>
int main()
{
char *c=333;
int *i=333;
long *l=333;
float *f=333;
double *d=333;
printf("c = %u, c+1 = %u",c,c+1);
return 0;
}

访问此链接:http://ideone.com/vnKZnx

我认为由于C++的强类型检查,这个程序肯定不能用C++编译。为什么这个程序用 C 编译?事实上,编译器也会显示警告。我正在使用 Orwell Dev C++ IDE(gcc 4.8.1 编译器)。我还在其他编译器 (Borland Turbo C++ 4.5) 上尝试了相同的程序,通过扩展名 .c 保存它,但在这个编译器上它编译失败。

最佳答案

这段代码既不是合法的 C 也不是合法的 C++。

N1570 §6.7.9/p11:

The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

§6.5.16.1/p1 规定了简单赋值:

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.

它们都不匹配左侧的指针和右侧的 333。 §6.5.16.1/p1 是一个约束,需要符合规范的实现才能在违反约束时生成诊断 (§5.1.1.3/p1):

A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint, even if the behavior is also explicitly specified as undefined or implementation-defined.

碰巧 GCC 决定在 C 模式下产生警告而不是错误并继续编译它,但它不必这样做。

关于c - 为什么这个执行无效指针初始化的程序在 C 中编译得很好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25725255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com