Not sure why the sign was *silently* lost when running this code. Any suggestions to prevent this at run time?
void print(int val){
cout<<"val: "<<val<<endl;
}
int main() {
print(-2147483648/2); // note that -2147483648/2 = -1073741824
print(-1073741824);
}
result display as:
val: 1073741824
val: -1073741824
Could you explain what had happened?
It won't work in this case
print((signed)-4294967294/2);
print(-2147483647);
result:
val: 1
val: -2147483647
Shouldn't I get a compiler error or runtime error? This subtle bug is quite nasty
you could make it a double.
You can make your int a signed long int that should give room for a big number.
It's likely that an int
without specifier is already long