Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned long long int strange behaviour

Tags:

c

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("\n x: %d \n y: %f \n",x,y);

works correctly and prints out

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 

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

like image 675
nareto Avatar asked Jan 19 '23 05:01

nareto


2 Answers

For the latter one use:

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

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

like image 98
Karoly Horvath Avatar answered Jan 29 '23 13:01

Karoly Horvath


You should use:

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

Otherwise something like this will happen (example is for system where unsigned long int is 4 byte, unsigned long long int is 8 byte and float is 4 byte):

  1. [[03 00 00 00] (unsigned long int) [3.0] (float)] everything is correct, you print two 4 byte values.
  2. [[03 00 00 00 00 00 00 00] (unsigned long long int) [3.0] (float)] here, you print two 4 print values, but actually in the buffer that your printf received there is one 8 byte value and one 4 byte value, so you prints only first 8 bytes :)
like image 32
Mihran Hovsepyan Avatar answered Jan 29 '23 12:01

Mihran Hovsepyan