lost sign of an integer

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
Use signed keyword:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

void print(int val){
cout<<"val: "<<val<<endl;
}

int main() {

print((signed)-2147483648/2);
print(-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

-4294967294 is too small as value for a 32 bit signed integer, see http://www.cplusplus.com/doc/tutorial/variables/
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
Topic archived. No new replies allowed.