espression with unsigned

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <iostream>

int main()
{
	
	unsigned u1 = 42, u2 = 10;

	std::cout << u2 - u1  << std::endl;

	system("pause");


}


sorry for the ignorance but are the beginning and I want to proceed knowing well the arguments and without a doubt ....

in this expression to subtract the value of u1 and u2 the value being negative returns me a wrong number, I do not understand what is the meaning of the expression itself, the value of the variable remains unchanged but how does the compiler know that the result can not be negative?

This expression is equivalent to

u2 = u2 - u1?
Since both u1 and u2 are of type unsigned, then the result of u2 - u1 will also be of the same type, unsigned.

This expression is equivalent to

u2 = u2 - u1?
No. Neither u1 nor u2 are changed when evaluating the result of the expression.

Also the result is not "wrong". It may be slightly surprising at first, that's all.
Last edited on
I do not understand what is the meaning of the expression itself
Let unsigned be the type of an n-bit integer, and let m = 2n. Then
(unsigned)u2 - (unsigned)u1
is equivalent to
(u2 + m - u1) % m
where x % y is the remainder of the integer division x / y.

This expression is equivalent to

u2 = u2 - u1?
No.

how does the compiler know that the result can not be negative?
Because unsigned values can never be negative.
Last edited on
Topic archived. No new replies allowed.