Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator: conversion from 'int ' to 'unsigned char ', possible loss of data

I have the following C code:

a = (b == B1) ? A1 : A2;

a, b, A1, A2 and B1 are all of type unsigned char. A1, A2 and B1 are all constants.

When compiling under VC++ I see the following warning:

warning C4244: '=' : conversion from 'int ' to 'unsigned char ', possible loss of data

I don't understand this warning - none of the variables are of type int. Presumably some kind of implicit conversion is happening, but why?

Strangely, the following code (which is functionally identical) compiles with no warnings:

if (b == B1) {
  a = A1;
} else {
  a = A2;
}

So far as I'm aware, the two code extracts should be identical.

like image 749
sam Avatar asked Nov 20 '25 08:11

sam


1 Answers

In C language arithmetic arguments of ternary ?: operator are subjected to usual arithmetic conversions, i.e. they are promoted to int before any further computations are performed. It doesn't really matter whether they are constants or not. What matters is that they have type unsigned char (as you said) and unsigned char under ?: is always promoted first. Basically, C language never performs any computations in types smaller than int. Everything smaller is converted to int first.

This is what happens in your case as well. Basically, your

a = (b == B1) ? A1 : A2;

is interpreted by C language as

a = ((int) b == (int) B1) ? (int) A1 : (int) A2;

and this is why you get the warning. Again, the fact that A1 and A2 are constants plays no role whatsoever.

The

a = A1;

does not subject the right-hand side to integral promotion, which is why there's no warning here. Moreover, in this trivial case (direct assignment) even if A1 was explicitly declared as an int constant, most compilers would not issue a warning if they could see that the constant is in range of the target type unsigned char. The case with ?: is more complicated, so the compilers might revert to the generic behavior and issue a warning.

like image 129
AnT Avatar answered Nov 21 '25 21:11

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!