if statement doesn't work as I expected

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
int a,b;
b = 2;

cout << "Please enter integer in range of –2,147,483,648 to 2,147,483,647 "<<endl;

cin >> a;
cout << "Thank you!"<<endl;

if (a < -2147483648 || a > 2147483647)
cout << "Enter a valid number!";
cout << "Remainder of a "<<a<<" divided by "<<b<<" is "<< a%b;

char fW;
cin >> fW;
return 0;

So when I eneter a value of variable a, which is in given range it just
prints out "Enter a valid number!"; so why if statement isn't working
Warning by gcc: warning: comparison is always false due to limited range of data type
Your if statement is pointless here: a will never be less than your value of larger than value.
For me it is working correctly giving remainder.
a is probably 32 bits, that means that when you enter a too large number for either ranges(- and +), it'll tend to stick at the highest possible number (according to my experience).

Let's draft a simple solution:

1. Instead of using an integer for direct assignment, use a string.
2. Iterate over the string.
3. if the size of the string > 10
4. - number too high
5. if the size of string == 9
6. - is first element (from left to right) higher than (char)2?
7. if yes, - number too high.
8. Is the first number less than (char) 2?
9. Valid input.
10. Is first number equal (char) 2?
- Check 2nd number equal (char) 1: check next..., if below, valid, if above, invalid.
Pardon me so why it's not working for me ?
I should say it's working for me as well (GCC on x64), taking the remainder.
Idk why is it true for you, try to print out a to see its value.

Although this check is really senseless since a can't be out of that range because it is of type int.

Bourgond Aries, you forgot check of the negative numbers, although this can be simply solved with check if first char is - and if it is increment starting index value.
Pardon me so why it's not working for me ?

You're using VC++ which doesn't behave correctly in this regard, from what I can determine, but it does give you a warning that you're blissfully ignoring:

warning C4146: unary minus operator applied to unsigned type, result still unsigned

which pretty much explains your results.

#include <limits>
#include <iostream>

using namespace std;

int main()
    std::cout << std::numeric_limits<int>::min() << '\n' ;
    std::cout << std::numeric_limits<long>::min() << '\n' ;
    std::cout << std::numeric_limits<long long>::min() << '\n' ;
    std::cout << -2147483648 << '\n' ;
    std::cout << -2147483649 << '\n' ;
Last edited on
Topic archived. No new replies allowed.