I am a bit confused about the behavior of c when it comes to adding large numbers. This is probably a beginner’s question but would appreciate any help.
unsigned long total = 0;
total = 1124073472 + 2835349503;
total += 2533359615;
printf("Total: %u\n", total);
The total which gets printed above is not correct. The first add result is fine but the third add throws the total off. I am thinking it is because of overflow. My question is what is a possible solution? Is there a solution without using third party libraries?
Note: I have tried various data types for total. Some of them are DWORD64, INT64, LONG64 etc.
Thanks in Advance.
You’re correct, it’s because of overflow. Using a 64-bit type will fix it – you will need to change your
printf()format string to printa 64-bit type too, though. Makingtotalanunsigned long longwill probably get you a 64-bit type, but the safest way would be to use one of the typedefs fromstdint.h. Here’s an example program – I also usedinttypes.hto getPRIu64.