简体   繁体   English

为什么这个 size_t i = size 变量在 for 循环中使用时给出“垃圾”值?

[英]Why does this size_t i = size variable giving "garbage" value when used in for loop?

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.我已经将 size 定义为 6 的传递值,跟踪“size”的值也产生了 6,但是当我使用 size,甚至是简单的 6 来初始化 i 但在 for 循环中, i 的值变成了垃圾。 In the case here i just initialize the value of 6 for easier interpretation.在这种情况下,我只是初始化 6 的值以便于解释。 To my best understanding, size_t is similar to an unsigned int or unsigned long int depending on the compiler据我所知,size_t 类似于 unsigned int 或 unsigned long int,具体取决于编译器

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

gcc -Wall -Wextra called and said hi: gcc -Wall -Wextra打来电话说你好:

warning: comparison of unsigned expression in '>= 0' is always true [-Wtype-limits]警告:'>= 0' 中无符号表达式的比较始终为真 [-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?帮自己一个忙,停止搜索编译器已经发现的错误,遵循以下建议:为初学者学习 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.当超过 0 时, size_t将因此获得一个非常大的整数值。

You then lie to printf and say that you are passing a signed long , when you are in fact passing an unsigned size_t .然后你对printf撒谎,说你正在传递一个有signed long ,而实际上你传递的是一个 unsigned size_t This is strictly speaking undefined behavior and anything can happen.严格来说,这是未定义的行为,任何事情都可能发生。 The correct conversion specifier to use is %zu .要使用的正确转换说明符是%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.实际上,在具有 8 位long的系统上,您可能会得到诸如 18446744073709551615 之类的输出,但这不能保证,因为它是一个错误。 In either case it is an eternal loop which will hang the program.在任何一种情况下,它都是一个永恒的循环,它将挂起程序。

i >= 0 is always true because i is a size_t and can't get under 0 i >= 0 始终为真,因为 i 是 size_t 并且不能低于 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.如果将 size_t 递减为 0,则此 size_t 将获得 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.如果您希望打印 0,您可以使用 i > 0 代替或使用for(int i = 6;i >= 0;--i)

PS : %zu is for size_t and %d for int (or %i , %d being for decimal integer input) PS: %zu 用于 size_t 和 %d 用于 int (或 %i , %d 用于十进制整数输入)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM