expression involving unsigned types

Write your question here.
can someone explain me why this program yeld this result ?


#include <iostream>

int main()
{
int a = 10; unsigned int b = 11;

std::cout << a - b << std::endl// result = 4294967264????



}
it's due to the standard:
ยง5/9 from the C++ Standard
if either operand is unsigned, the other shall be converted to unsigned.


10 - 11 = -1.
-1 in two complements is 0xffffffff which is 4294967295 decimally.
1
2
std::cout << (unsigned)0xffffffff //print: 0xffffffff 
std::cout << (int)0xffffffff // print: -1 
It's related to how the compiler matches the types of variables in an expression before carrying out the subtraction.

You can control the result either by assigning the result of the expression to a variable of the desired type, or by casting it to the required type.
1
2
3
4
5
6
7
8
9
10
    int          a = 10; 
    unsigned int b = 11;
    int          c = a - b;
    unsigned int d = a - b;
    
    std::cout << "a - b             " << a - b << std::endl;
    std::cout << "cast to int       " << static_cast<int>(a - b) << std::endl;
    std::cout << "cast to unsigned  " << static_cast<unsigned int>(a - b) << std::endl;
    std::cout << "int c             " << c << std::endl;
    std::cout << "unsigned int d    " << d << std::endl;

a - b             4294967295
cast to int       -1
cast to unsigned  4294967295
int c             -1
unsigned int d    4294967295

As to why a very large number is displayed, that comes down to the way that negative numbers are represented in twos complement form.
Last edited on
@tath

so the compiler before execute the expression a - b then converts the value of a from int to unsigned int ?
Last edited on
if either operand is unsigned, the other shall be converted to unsigned.


so - yeah.
Topic archived. No new replies allowed.