Type of a expression

Consider this code:
1
2
unsigned char alpha   = 0xff;
unsigned short result = alpha << 12;


I thought that expression alpha << 12 results in 0 as 'alpha' is 'unsigned char' and then assigns 0 to 'result' (unsigned short), but it does not.

What about literal constants (with mixed types), for example:
1
2
signed int a = -5;
... (120u / a) > 0 


My guess is that compiler makes some implicit casts but i don't know these "rules" when it does? On what it depends on?
Last edited on
All types that are smaller than int are promoted to int when they are used in an expression.

In your code alpha is treated as an int and that's why you not get 0.

The rules for types larger than int is a bit different. If you mix two unsigned and signed types of the same size the signed value will be treated a unsigned so 120u / a is actually the same as 120u / (unsigned) a.

For types of different size I think the smaller type is just converted to the larger type.
So it depends on the type of lvalue on the left side of the '=' sign.
Thanks.
> So it depends on the type of lvalue on the left side of the '=' sign.

No, it does not.
1
2
char c = 'a' ;
decltype(+c) b ; // type of b is int 
Last edited on
Topic archived. No new replies allowed.