Tool/software: TI C/C++ Compiler
Hello,
We're testing new compiler release 8.3.4 and verified (also with CGT 8.3.6), that there is compilation failure with some specific circumstances, which didn't appear with CGT7. I'm attaching sample code (with command to build) to reproduce issue:
typedef enum
{
a = 1,
b,
c
} X;
unsigned fun(X param)
{
const unsigned int y[] = { param };
return y[0];
}
int main()
{
unsigned i = 0;
i = fun(c);
if(i>0)
{
;
}
}
Compiler error:
"./main.cpp", line 10: error #2721-D: invalid narrowing conversion from "X" to "unsigned int"
1 error detected in the compilation of "./main.cpp".
>> Compilation failure
Deeper investigation was made with online compilers from wandbox to have reference results (both GCC/Clang checked). Initial reference code:
#include<iostream>
#include<limits.h>
typedef enum
{
a = 1,
b,
c
} X;
void fun(X param)
{
const unsigned int y[] = { param };
std::cout << "Value of y=" << y[0] << std::endl;
}
int main()
{
const unsigned int x[] = { a, b, c};
fun(c);
std::cout << "Values: " << x[0] << ", " << sizeof(a) << ", " << sizeof(X) << std::endl;
}
with output:
Error we observed with CGT was introduced by C++11 - narrowing conversion for array initialization means program is ill-formed (find "narrowing conversion" phrase here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf). To trigger this error, code can be changed slightly:
#include<iostream>
#include<limits.h>
typedef enum
{
a = 1,
b = UINT_MAX,
c
} X;
void fun(X param)
{
const unsigned int y[] = { param };
std::cout << "Value of y=" << y[0] << std::endl;
}
int main()
{
const unsigned int x[] = { a, b, c}; // Works with b = 2, doesn't work with b = UINT_MAX
fun(c); // Causes error.
std::cout << "Values: " << x[0] << ", " << sizeof(a) << ", " << sizeof(X) << std::endl;
}
Error detected:
prog.cc: In function 'void fun(X)':
prog.cc:14:32: error: narrowing conversion of 'param' from 'long unsigned int' to 'unsigned int' [-Wnarrowing]
14 | const unsigned int y[] = { param };
| ^~~~~
prog.cc: In function 'int main()':
prog.cc:21:39: error: narrowing conversion of 'c' from 'long unsigned int' to 'unsigned int' [-Wnarrowing]
21 | const unsigned int x[] = { a, b, c}; // Works with b = 2, doesn't work with b = UINT_MAX
| ^
1
To have well-formed program, it should be modified:
#include<iostream>
#include<limits.h>
typedef enum
{
a = 1,
b = UINT_MAX,
c
} X;
void fun(X param)
{
const unsigned long int y[] = { param };
std::cout << "Value of y=" << y[0] << std::endl;
}
int main()
{
const unsigned int x[] = { a };
fun(c);
std::cout << "Values: " << x[0] << ", " << sizeof(a) << ", " << sizeof(X) << std::endl;
}
Value of y=4294967296
Values: 1, 8, 8
0