Reputation: 61
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.
Upvotes: 1
Views: 1608
Reputation: 1600
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.
Upvotes: 6
Reputation: 26800
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.
Upvotes: 3