简体   繁体   English

以下分配仅导致警告。 关于C如何对待类型等价,这说了什么?

[英]The following assignment only causes a warning. What does this say about how C treats type equivalence?

The following assignment only causes a warning. 以下分配仅导致警告。 What does this say about how C treats type equivalence? 关于C如何对待类型等价,这说了什么?

int *iptr;
float *fptr;
float fval;
fval = 0.0;
fptr = &fval;
iptr = fptr;

In particular, I'm referring to the assignment in the last line of the above snippet of code; 特别是,我指的是上面代码片段的最后一行中的赋值; namely, 即,

iptr = fptr;

It says more about the behavior of the compiler you're using than about C, though the compiler's behavior is (unfortunately IMHO) permitted by the C standard. 它更多地说明了你使用的编译器的行为而不是关于C的行为,尽管C标准允许编译器的行为(不幸的是恕我直言)。

The types int* and float* are distinct, and the language defines no implicit conversion between them. int*float*类型是不同的,语言定义它们之间没有隐式转换。

Attempting to assign one to the other without a cast (ie, an explicit type conversion) is a constraint violation , which means that a compiler is required to issue a diagnostic message. 尝试在没有强制转换的情况下将一个分配给另一个(即显式类型转换)是违反约束 ,这意味着需要编译器发出诊断消息。

The C standard does not require such a diagnostic to be fatal. C标准不要求这种诊断是致命的。 By issuing a warning, your compiler has done its job as far as the C standard is concerned. 通过发出警告,就C标准而言,编译器已完成其工作。 It could, with equal validity, have rejected your program (and in my opinion that would have been more user-friendly). 它可以在相同的有效性下拒绝您的程序(在我看来,这将更加用户友好)。 But either behavior is conforming. 但这两种行为都是一致的。

You can probably invoke your compiler in a way to make it treat this as a fatal error. 您可以以某种方式调用编译器,使其将其视为致命错误。 For example, if you're using gcc the -pedantic-errors option (along with an option to specify which version of the C standard to use) should do the trick. 例如,如果您正在使用gcc -pedantic-errors选项(以及指定要使用哪个版本的C标准的选项)应该可以解决问题。

If you really want to perform that assignment (with all the risks that entails), you can use a cast: 如果你真的想要执行该任务(包含所有需要的风险),你可以使用强制转换:

iptr = (int*)fptr;

In addition to (probably) turning off the compiler warning, a pointer cast should act as a reminder that you're doing something tricky, and it may blow up in your face if you don'w know exactly what you're doing. 除了(可能)关闭编译器警告,指针应该投作为你正在做的事情非常棘手的提醒,它可能在你的脸上吹,如果你don'w知道你在做什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM