evaluating an expression of signed and unsigned types

hello everybody....could you explain me what happens exactly in this expression ?

1
2
3
4
5
6
7
8
9
unsigned int j = 10; 
	int k = -42; 
	 
	std::cout << j - k << std::endl; 
	
//here is created an unsigned temporary wich value is the value of k that wraps 
//around
//then the expression should be 10 - 4294967254


why the result is 52 and not another int big value ? i want to know how the language works but i'm a beginner and sometimes it's hard to learn how to program.

The expression is actually:

std::cout << 10 - -42 << std::endl;

which is rather math than programming related
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <iomanip>

int main()
{
    unsigned int j = 10;
    int k = -42;

	// evaluate j - k. first apply 'usual arithmetic conversions' (in this case integral conversions)
	// http://en.cppreference.com/w/cpp/language/operator_arithmetic#Conversions
    
	// unsigned int and signed int have the same conversion rank
	// the unsigned operand's conversion rank is equal to the conversion rank of the signed operand,
	// so the signed operand is converted to the unsigned operand's type.
	unsigned int k_converted = k ;

	std::cout << std::hex << std::showbase << std::internal
	          << std::setw(30) << "value of j is "
	          << std::setw(10) << std::setfill('0') << j << '\n' << std::setfill(' ')
	          << std::setw(30) << "value of k_converted is "
	          << std::setw(10) << std::setfill('0') << k_converted << '\n' << std::setfill(' ')
	          << std::setw(30) << "value of j - k_converted is "
	          << std::setw(10) << std::setfill('0') << j - k_converted << '\n' << std::setfill(' ') ;

	std::cout << std::dec << std::setw(30) << "or decimal "
	          << std::setw(10) << std::setfill('0') << j - k_converted << '\n' ;

	std::cout << 1 - 2U << ' ' << '\n' ; // 4294967295 with 32-bit int (0xffffffff)
	std::cout << signed( 1 - 2U ) << '\n' ; // -1 (result converted to signed int)
}

http://coliru.stacked-crooked.com/a/83deff92810fbaa9
Topic archived. No new replies allowed.