0

I am trying to perform the following

#include <stdio.h>
#include <stdint.h>
int main()
{

     unsigned long long test = 100; //64 bits
     test = test + (1UL << 33); //assuming 64 bits

     printf("test value %u", test);

     return 0;

}

test prints 100. I was expecting it to add the shifted bit to it.

I can see that there is some issue with its size, as if I, for example add 1UL << 14 test would be equal to 16484.

I am testing it out here: https://onlinegdb.com/r1njSlGjU

How can I go about adding this? I noticed that on my gdb debugger, the code just skips the line that adds does the addition.

Hadi
  • 945
  • 3
  • 10
  • 31
  • Enable all compiler warnings. Hopefully you'll get something like "warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'long long unsigned int'" - faster than posting on SO. – chux - Reinstate Monica May 20 '20 at 01:59
  • I did see the warning..didn't occur to me that a zero output was related to the warning. – Hadi May 20 '20 at 03:41

2 Answers2

4

The printf function has different formats for different data types. You are using a variable with 'unsigned long long' type but in the printf you are using "%u" which only prints objects of the type "unsigned int". By giving it the wrong 'data type' specifier you cause an undefined behavior. You may refer to the wikipedia: https://en.wikipedia.org/wiki/C_data_types.

For the right output:

printf("test value %llu", test);
Sean Tashlik
  • 176
  • 8
1

It actually is adding the value, you just don't realize it, since you're printing it out with %u. This converts the value to an unsigned int, which means that it's just 100. If you print with %llu for unsigned long long, it'll print out correctly.

Aplet123
  • 33,825
  • 1
  • 29
  • 55