Case 1. File: test1.c
:
unsigned long val = (unsigned long)&"test";
int main()
{
return 0;
}
Compiler invocation: cl test1.c /c
Results:
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
Case 2. File: test2.c
:
union { unsigned long val; } val = { (unsigned long)&"test" };
int main()
{
return 0;
}
Compiler invocation: cl test2.c /c
Results:
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'
Question: why after putting unsigned long
into union
(case 2, file test2.c) the error C2099: initializer is not a constant
is gone?
Notes:
for both code versions
cl x86
(same version as for x64) produces NO errors, NO warnings.for both code versions
gcc x86/x64
(version 9.3.0) produces NO errors, NO warnings.
UPD. Please note: the question is not about safe code / unsafe code
or wrong code / right code
. The question is about cl
compiler behavior. I.e. why in the 2nd case the cl considers that initializer IS a constant
(such conclusion is from the absence of the error message).