But if absolute value of i is less than u it seems like no such conversion is hapenning.
Your assumption is wrong: such conversion is happening. And by "such conversion", I mean that when -3 was converted to the unsigned type, the result was 4'294'967'293.
I haven't seen any answer mentioning it and can't find any explanation.
Unsigned arithmetic is modular. This is simply how modular arithmetic works.
To understand modular arithmetic, think for example how a 12 hour clock works. It is also modular. You'll notice that the clock face doesn't have any negative numbers:
- Time is 10 (am, today). 3 hours ago, what was the time? It was 7 (am, today).
- Time is 10 (am, today). 42 hours ago, what was the time? It was 4 (pm, day before yesterday)
Unsigned arithmetic works exactly like that. Except, instead of 12 values, there are 4'294'967'296 values in case of 32 bit type.
In order to convert an unrepresentable value into the representable range, simply add or subtract the modulo (12 in case of clock, 4'294'967'296 in case of 32 bit unsigned integer) until the value is in the representable range.
Here is the math for the clock examples:
R ≡ 10 + (-3) (mod 12)
// -3 = 9 + (12 * -1)
R ≡ 10 + 9 (mod 12)
R ≡ 19 (mod 12)
// 19 = 7 + (12 * 1)
R ≡ 7 (mod 12)
R ≡ 10 + (-42) (mod 12)
// -42 = 6 + (12 * -4)
R ≡ 10 + 6 (mod 12)
R ≡ 16 (mod 12)
// 16 = 4 + (12 * 1)
R ≡ 4 (mod 12)
Here is the math for your examples:
R ≡ 10 + (-42) (mod 4'294'967'296)
// -42 = 4'294'967'254 + (4'294'967'296 * -1)
R ≡ 10 + 4'294'967'254 (mod 4'294'967'296)
R ≡ 4'294'967'264 (mod 4'294'967'296)
R ≡ 10 + (-3) (mod 4'294'967'296)
// -3 = 4'294'967'293 + (4'294'967'296 * -1)
R ≡ 10 + 4'294'967'293 (mod 4'294'967'296)
R ≡ 4'294'967'303 (mod 4'294'967'296)
// 4'294'967'303 = 7 + (4'294'967'296 * -1)
R ≡ 7 (mod 4'294'967'296)
7
and an unsigned7
? – Ultimodecltype
andstd::is_same_v
. (Or print it with a number of tricks in articles out there for printing types.) – Stipitatestd::cout
on the screen not the integer literal7
. Nevermind, I completely misunderstood the question at first and that was the reason for asking stupid questions – Ultimo