0

Please... Explain...

#include <stdio.h> int main() { unsigned int i; int c=0; for(i=0;i<10;i--)c++; printf("%d",c); return 0; } //Output is 1 // How ?

21st May 2019, 11:17 AM
Sp Maurya
Sp Maurya - avatar
2 Réponses
+ 5
i is unsigned, it can't take a negative value. If i is 0 and you subtract 1, the result won't be -1 but a huge number (because of an overflow). You can prove it like this: int main() { unsigned int i = 0; printf("i > 100? %d\n", i > 100); // 0 (no, 0 is not > 100) --i; // i = 0 - 1, but it can't take a negative value => overflow printf("i > 100? %d\n", i > 100); // 1 (yes, 0-1 is > 100 for an unsigned integer) return 0; } That's why after i-- the condition i < 10 is false and the loop will only be executed once. c is incremented once => c = 1
21st May 2019, 12:15 PM
Anna
Anna - avatar
+ 3
thank you so much i got it...
22nd May 2019, 8:34 AM
Sp Maurya
Sp Maurya - avatar