3 ms·
While we are talking about C skills, recently I got hit by this gotcha. I never knew a simple comparision could be this complex. Question: Whats ru, rs ?
by wav-part 9y ago
While we are talking about C skills, recently I got hit by this gotcha. I never knew a simple comparision could be this complex.
Question: Whats ru, rs ?
unsigned int u0 = 0;
unsigned int u1 = 1;
int s0 = 0;
int s1 = 1;
int ru = 0 > u0 - u1;
int rs = 0 > s0 - s1;
Answer: ru is 0. rs is 1.
- jonsen 9y agoI wouldn't say it is complex, that we have unsigned comparison for unsigned numbers, and signed comparison for signed numbers.
- MaulingMonkey 9y agoFor this specific case, warnings can save you: https://wandbox.org/permlink/wwbCYysH039z3YqN https://wandbox.org/permlink/wwbCYysH039z3YqN prog.cc: In function 'int main()': prog.cc:8:16: error: comparison of unsigned expression < 0 is always false [-Werror=type-limits] int ru = 0 > u0 - u1; ~~^~~~~~~~~
- wav-part 9y agoI had -Wall set but I forgot that its misleading. -Wextra is needed for -Wtype-limits and -Wsign-compare.