I have a problem of different results produced by a simple C++ code compiled on macOS 11 with
clang version 14.0.6 Target: x86_64-apple-darwin20.6.0
The program is the following:
#include <stdio.h>
template<typename T, typename U, typename O> inline static void add(T* l, size_t size, U r, O* o)
{
for (size_t i = 0; i < size ; ++i)
{
o[i] = (O)l[i] + (O)r;
}
}
int main()
{
double x[4] = {-1,-1,-1,-1};
unsigned char y = 127;
unsigned char z[4];
add(x, 4, y, z);
for (size_t i = 0; i < 4; i++)
{
printf("z[%zu]=%u\n",i,z[i]);
}
}
and the to different results are (with and without -O2
optimization):
$ clang -O2 add.cpp -o add; ./add
z[0]=0
z[1]=0
z[2]=0
z[3]=0
$ clang add.cpp -o add; ./add
z[0]=126
z[1]=126
z[2]=126
z[3]=126
correct result is the one without optimization. How can I have the correct results when using optimization ?