1

I am new to C programming and trying to understand data types.

I specified following variables:

  int nsamples = 10000000;
  int n = 32;
  int m = 64;


  int nrpoinnts = n*m*nsamples+99;
  printf("Nr points %d\n",nrpoinnts);

For some reason the printed number is negative. Why is that happening? I tough the value range of nrpoinnts was exceeded, so I checked double. The final result was that I was getting negative value either.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
EveSz
  • 61
  • 6
  • 4
    Because it overflows the max positive 32 bit integer. Try using long long integer and %lld. – ulix Oct 10 '18 at 04:07
  • 1
    check [integer overflow](https://stackoverflow.com/questions/9052088/why-int-i-400400-400-gives-result-72-is-datatype-circular) for a proper explanation. – Imran Rana Oct 10 '18 at 04:19
  • If you want to check the value using `double`, you need to force at least one of `n`, `m` or `nsamples` to a floating point value in the calculation as otherwise the calculation is done using integer arithmetic and the result converted to `double`. Hence: `double num_points = (double)n * m * nsamples + 99;` would yield a positive floating point value. – Jonathan Leffler Oct 10 '18 at 05:26

3 Answers3

6

The limit/range of signed int or just int you are using, even on a 64 bit machine with a 4 byte integer is 2,147,483,647 (as its maximum value) and −2,147,483,648 (as its minimum value) - the value you are trying to generate/print is 20480000000 which is greater than the limit/range - hence it is wrapping and producing -ve results.

Example:

#include<stdio.h>

int main()
{
    printf("%d\n",2147483647+1);
    return 0;
}

OUTPUT: −2147483648

Use long unsigned instead of int to contain the result.

Gaurav
  • 1,570
  • 5
  • 17
3

The value of your multiplication is 20,480,000,000. If int is 4 bytes long on your system, then the maximum value it can have is 2,147,483,647. You can check the value of INT_MIN and INT_MAX macros defined in limits.h The values of both these macros are compiler dependent because sizeof(int) is implementation defined in both C & C++.

When this INT_MAX value is exceeded, it prints a negative value in this particular instance. But note that signed integer overflow is undefined behaviour as per the standard.

So, you can use unsigned long long instead of int to store the value of your arithmetic operation.

P.W
  • 26,289
  • 6
  • 39
  • 76
2

change

 int nrpoinnts

to

 unsigned long int nrpoinnts
Kaidi Wang
  • 33
  • 4