Unsigned long long int strange behavior

this C code

unsigned long int a, b, x; float c, d, y; a = 6; b = 2; x = a/b; c = 6.0; d = 2.0; y = c/d; printf("\nx: %d \ny: %f \n",x,y); 

works correctly and prints

 x: 3 y: 3.000000 

however, when I change the first line to this

 unsigned long long int a, b, x; 

I get this output:

 x: 3 y: 0.000000 

it really clogs me ... I haven't changed anything with c, d and y - why am I getting this? I am using gcc on linux

+4
source share
2 answers

For the latter, use:

 printf("\nx: %llu \ny: %f \n",x,y); 

Use u for unsigned integrals (your output is correct because you use small values). Use the ll modifier for long lengths, otherwise printf will use the wrong size to decode the second parameter (x) for printf, so it uses the wrong address to select y.

+7
source

You should use:

 printf("\nx: %llu \ny: %f \n", x, y); 

Otherwise, something similar will happen (example for a system where unsigned long int is 4 bytes, unsigned long long int is 8 bytes, and float is 4 bytes):

  • [[03 00 00 00] (unsigned long int) [3.0] (float)] everything is correct, you print two 4 byte values.
  • [[03 00 00 00 00 00 00 00] (unsigned long long int) [3.0] (float)] here you print two 4 print values, but in reality there is one 8-byte value in the buffer that your printf received and one 4-byte value, so you only print the first 8 bytes :)
+2
source

All Articles