What are signed and unsigned keywords in C++?

C++Server Side ProgrammingProgramming

All number types in C++ can either have a sign or not. For example, you can declare an int to only represent positive integers. Unless otherwise specified, all integer data types are signed data types, i.e. they have values which can be positive or negative. The unsigned keyword can be used to declare variables without signs.

Example

#include<iostream>
using namespace std;

int main() {
   unsigned int i = -1;
   int x = i;
   cout << i << ", " << x;
   return 0;
}

Output

This will give the output −

4294967295, -1

This output is given because it overflows the int by changing all 0 in the bit representation to 1s and max value of int is printed. This is because now the int i doesn't have a sign.  But x has a sign so it'll have the value -1 only.

raja
Published on 15-Feb-2018 07:50:15
Advertisements