if statement to read number negative or positive not working

So I tried creating a test code for reading a negative number and positive number but whenever I enter a negative number it read it as being positive.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
	unsigned char un1;
	cout<<"Please input your first decimal number \n"<<endl;
	cin>>un1;
	if(un1<=-1)
	{
		cout<<"you enter negative number";
	}
	else
	{
		cout<<"you entered a positive number";
	}
									
}


My output

Please input your first decimal number

-1
you entered a positive number


PS: I am using char over int because the program that I am testing for requires me to use 8 bit variable.
What is the type of un1?

What is range of values which can be stored in that type?
the value -1 is type of int, so when you compare un1 <= -1, at this moment, the un1's type will implicitly convert to int. it' s equal to (int)un1 <= -1.

as un1 is ranged from 0x00 to 0xff, and it's unsigned , so (int)un1 is from 0x00000000 t0 0x000000ff(0 to 255), so un1 <= -1 will always be false.

if un1 you declared as char, the situation will be very different.
the padded bits will defend on the MSB of un1, for example:

if char un1 = 0xff,
then (int)un1 will be 0xffffffff(if un1 is unsigned, the result is 0x000000ff)



so i advise you to declare un1 as char(int is better)
Last edited on
Topic archived. No new replies allowed.