Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning - Integer operation result is out of range in c

Tags:

c

gcc

I'm using RVCT compiler to compile this code in C (relevant section here):

static void Test (void)
{
     unsigned long regVal;
     regVal |= (UINT32)(    (0x1 << 31)     |
                            (0x1 << 26)     |
                             0x3E);
}

When compiling the code, I receive the following warning Warning: " #61-D: integer operation result is out of range".

I would like to understand what to change in order to avoid the warning.

Thank you in advance!

like image 926
dear_tzvi Avatar asked Aug 06 '13 13:08

dear_tzvi


2 Answers

Due to integer promotion rules, the inner expression (i.e. before the (UINT32) cast) is treated as signed int. Therefore, 0x1 << 31 is 0x80000000, which is a negative signed integer, thus resulting in the warning. To fix, you can force the shifts to be unsigned by appending 'U' to the hex constants, like 0x1U.

 regVal |= (UINT32)(    (0x1U << 31)     |
                        (0x1U << 26)     |
                         0x3EU);

This will force all of the shifts and bitwise ORs to be unsigned, which should get rid of the warning (and also removes the need for the (UINT32) cast, since it's already unsigned).

like image 69
Drew McGowen Avatar answered Nov 20 '22 08:11

Drew McGowen


The compiler overflow warning is correct, because the expression 1<<31 represents a signed int. To avoid the warning, explicitly define the constant 0x1 as an unsigned value using the U postfix. For example:

unsigned long regVal;
regVal |= (UINT32)(    (0x1U << 31)     |
                        (0x1 << 26)     |
                         0x3E);
like image 35
No Idea For Name Avatar answered Nov 20 '22 09:11

No Idea For Name