Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

puzzled by compiler warning that suggests compound assignment of int8_t promotes to int

Tags:

c++

c

standards

icc

I can usually understand the reason behind a compiler warning, but this one seems just plain wrong.

#include <stdint.h>    
uint8_t myfunc(uint8_t x,uint8_t y)
{
    x |= y;
    return x;
}

The intel compiler with -Wall complains:

conversion from "int" to "uint8_t={unsigned char}" may lose significant bits
  x |= y;
    ^

Is this right? Is the above code non-portable and non-standard somehow?

like image 411
Mark Borgerding Avatar asked May 03 '11 14:05

Mark Borgerding


3 Answers

That's integer promotions at work.

in

x |= y;

both operands of the | operator are promoted to int

x = (int)x | (int)y;

then the result is converted back to uint8_t losing precision.

like image 121
pmg Avatar answered Oct 20 '22 22:10

pmg


It is right. The operator promotes the argument(s) to int. See this page for more details, the first sentence begins:

No arithmetic is done by C at a precision shorter than int [...]

like image 21
unwind Avatar answered Oct 20 '22 22:10

unwind


The values of x and y are promoted to int for the computation, but the warning is nonetheless bogus. The | operator cannot increase the width in bits of the result beyond the widths of the operands, which already fit in uint8_t since they were promoted from uint8_t. The vast majority of things this warning option flags are completely valid and correct code, and unless you want to waste your time on 100 questions like this, I think it's best to turn off or ignore those warnings.

like image 4
R.. GitHub STOP HELPING ICE Avatar answered Oct 20 '22 22:10

R.. GitHub STOP HELPING ICE