Home > Blockchain >  Calculation of higher values in C
Calculation of higher values in C

Time:03-22

The following code is not working properly. I wanted it to print the sum of 2 billion 2 billion. Even though I'm using long here, I can't get the answer correct.

#include<stdio.h>
#include<stdlib.h>

int main(void){

long  a = 2000000000;
long  b = 2000000000;

printf("%li\n",a   b);

return 0;
}

When I run this program I get the value -294967296. I'm using VS Code IDE, Mingw compiler and windows version is windows 11.

CodePudding user response:

long is at least 32-bit and its range must span at least /- 231 - 1 or /-2,147,483,647.

On some machines a long is wider such as [-263 ... 263 - 1].

On OP's machine, it is [-231 ... 231 - 1].


For OP. a b inccurs signed integer overflow which in undefined behavior (UB) as the sum of two long is outside the long range. A common result is the sum is "wrapped" and results in a long of -294,967,296 although many other results are possible including code crash.


To handle sums like 4,000,000,000, perform the addition with unsigned long math with its minimum rage of [0 ... 232 - 1] or use long long.

// printf("%li\n",a   b);
printf("%lli\n",0LL   a   b);

Or ...

long long  a = 2000000000;
long long  b = 2000000000;
printf("%lli\n",a   b);

CodePudding user response:

The size of long integer is not fixed unlike other data types. It varies from architectures, operating system and even with compiler that we are using. In some of the systems it behaves like an int data type or a long long data type as follows:


  OS               Architecture          Size
Windows       IA-32                     4 bytes
Windows       Intel® 64 or IA-64        4 bytes
Linux         IA-32                     4 bytes
Linux         Intel® 64 or IA-64        8 bytes
Mac OS X      IA-32                     4 bytes
Mac OS X      Intel® 64 or IA-64        8 bytes 

long might be 32 bit in your case. To avoid this confusion, use stdint where you can be sure of the sizes and also portable

#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<inttypes.h>

int main(void){

    int64_t  a = 2000000000;
    int64_t  b = 2000000000;

    // printf("%lli\n",a   b);
    printf("res = %" PRI64d "!\n", a b);

    return 0;
}


CodePudding user response:

The max size of a long may be the same as an int, you should use long long instead.

Integer size in C

  • Related