Home > OS >  Why does this size_t i = size variable giving "garbage" value when used in for loop?
Why does this size_t i = size variable giving "garbage" value when used in for loop?

Time:10-15

I have defined size as the passed value of 6 tracing the value of "size" also produced 6, however when I use size, or even plainly 6 to initialize i but in the for-loop, the value of i goes to garbage. In the case here i just initialize the value of 6 for easier interpretation. To my best understanding, size_t is similar to an unsigned int or unsigned long int depending on the compiler

for (size_t i = 6 ; i >= 0; --i){
        printf("%lu\n",i);
    }

CodePudding user response:

gcc -Wall -Wextra called and said hi:

warning: comparison of unsigned expression in '>= 0' is always true [-Wtype-limits]

Do yourself a favour and stop searching for bugs that the compiler already found, by following this advise: What compiler options are recommended for beginners learning C?


Now what happens in this case is that unsigned integers have well-defined wrap around. When going past 0, size_t will therefore get the value of a very large integer.

You then lie to printf and say that you are passing a signed long, when you are in fact passing an unsigned size_t. This is strictly speaking undefined behavior and anything can happen. The correct conversion specifier to use is %zu.

In practice on a system with 8 bit long, you might get an output such as 18446744073709551615, but this isn't guaranteed since it's a bug. In either case it is an eternal loop which will hang the program.

CodePudding user response:

i >= 0 is always true because i is a size_t and can't get under 0

So the loop won't terminate, this is something your compiler accepts or not depending your compilation options

If you decrement a size_t which is equal to 0, this size_t will get the largest possible value for size_t.

You can use i > 0 instead or use for(int i = 6;i >= 0;--i) if you want your 0 to be printed.

PS : %zu is for size_t and %d for int (or %i , %d being for decimal integer input)

  • Related