gcc Unexpected behavior for return value of endian swapping function In C. Function returns 0 with return statement and the parameter with none

0

Can someone help me understand this behaviour. For some reason when I use a return statement at the end of the function the function returns 0 with no return statement I get the correct value:

Version with no return statement returns the value itself (Not the correct value as previously believed)

uint32_t swap_u32(uint32_t value)
{
  ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24);
}

Version with return statement returns 0:

uint32_t swap_u32(uint32_t value)
{
  return ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24);
}

I call the function like so:


call_function(swap_u32(state->phase));

Example:


uint32_t x = swap_u32(50)
printf("%x", 50)
printf("%x", x)

Expected Output:

# hex value before swap which is same as 00000032 or 0x00000032
32

# swapped value in hex 0x32000000
32000000 

I am using gcc 7.5.0

I am compiling using the following flags

gcc filename.c -Wall -pedantic -Wextra

I get the expected warning of no return statement if I exclude the return statement.

control reaches end of non-void function [-Wreturn-type]

New behavior after review (Not sure if I should add this as an answer)

Turns out there was no swapping happening instead the function just returned the parameter as is. that is if the value was 50 function just returned 50. Also not sure why this is.

Solution To previous problem :

Instead of returning the expression store it in an lvalue then return. Again not sure why this works

uint32_t swap_u32(uint32_t value)
{
  value = (((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24));
  return value;
}
c
gcc
endianness
asked on Stack Overflow Apr 25, 2020 by Faridah Namutebi • edited Apr 25, 2020 by Faridah Namutebi

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0