PDA

View Full Version : Strict-aliasing and old-style-cast problem with C to C++ code



taraj
18th October 2016, 03:10
Hi,

I have some c code that I have put into my qt5 program but I get a lot of old-style-cast warnings which I would like to get rid of but don't quite know how to. I have tried reinterpret_cast but either I'm doing it incorrectly or it is not the right thing to do as it still results in the same error... :(

Thanks in advance!


warning: use of old-style cast [-Wold-style-cast]
warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]

Example code:

unsigned int j,k;
unsigned int* jj;
char* cptr;
char buff[50];

jj = (unsigned int*)&tmpY; //recast as int as expected in htonl
j = htonl(*jj); //convert to network format
cptr = (char*)&j; //recast as a char * so can use indexing
sprintf(buff,"Y=%7.2f ",tmpY);
tmp=buff;
s.append(buff);
for(i=0;i<YLen;i++)
{
msg[YIndex+i] = cptr[i];
}

jefftee
23rd October 2016, 18:42
reinterpret_cast, static_cast, dynamic_cast and const_cast are the c++ cast alternatives. Google around to read why to use one over the others, etc.