情况1。文件:test1.c
:
unsigned long val = (unsigned long)&"test";
int main()
{
return 0;
}
编译器调用:cl test1.c /c
结果:
microsoft (R) C/C++ Optimizing Compiler Version 19.25.28611 for x64
Copyright (C) microsoft Corporation. All rights reserved.
test1.c
test1.c(1): warning C4311: 'type cast': pointer truncation from 'char (*)[5]' to 'unsigned long'
test1.c(1): error C2099: initializer is not a constant
情况2。文件:test2.c
:
union { unsigned long val; } val = { (unsigned long)&"test" };
int main()
{
return 0;
}
编译器调用:cl test2.c /c
结果:
microsoft (R) C/C++ Optimizing Compiler Version 19.25.28611 for x64
Copyright (C) microsoft Corporation. All rights reserved.
test2.c
test2.c(1): warning C4311: 'type cast': pointer truncation from 'char (*)[5]' to 'unsigned long'
问题:为什么将unsigned long
放入union
(案例2,文件test2.c)之后,error C2099: initializer is not a constant
消失了?
注意:
-
对于两个代码版本
-
都不会产生错误,也不会发出警告。
两种代码版本 -
都不会产生错误,也不会发出警告。
cl x86
(与x64相同的版本),gcc x86/x64
(版本9.3.0)的 UPD。请注意:问题与safe code / unsafe code
或wrong code / right code
有关。问题是关于cl
编译器的行为。即为什么在第二种情况下,cl认为initializer IS a constant
(这种结论是由于没有错误消息)。