GCC changing signdess whole expression

75 views Asked by At

I have the following code:

unsigned int m_font_timer = 0;

int Getsum(int p_top_left_x)
{
    int l_sum = (((p_top_left_x + (m_font_timer >> 2)) & 0x7) - 4 ) >> 2;
    
    if (l_sum < 0) l_sum = -l_sum;
    return l_sum;
}

Unless I explicitly cast m_font_timer to (signed int) this part of the expression becomes unsigned:

((p_top_left_x + (m_font_timer >> 2)) & 0x7) - 4 );

Even though there is a "-4" and p_top_left_x is signed.

This is happening on a crosscompiler for SH4 using gcc 4.7.3 (I'm programming for an old system that requires it). I wasn't expecting that part to turn into unsigned. I have this code running on two other platforms also with GCC (higher version than this one) and one with MSCV and they all keep the aforementioned expression as signed.

I don't know much about compilers, is this undefined behavior? Is there any way the compiler would warn me about this? I have -Wall -Wformat=0 -Wextra -Wsign-compare but doesn't rise any warnings in that function.

Thanks!

1

There are 1 answers

2
Uriel.Gi On BEST ANSWER

Type conversion works by rank and signedness: If the types are of different rank - as in int and char, the lower rank (char) will get converted to the higher rank (int).

If both types are of the same rank but the sign is different - the signed type will be converted to unsigned unless explicitly stated otherwise.

Here are a few places which explain in detail:

usual arithmatic conversion

another source