简体   繁体   English

即使不满足条件,C 'for' 循环也会继续

[英]C 'for' loop continuing even when condition is not met

I have a simple function in C that calculates days between two given dates.我在 C 中有一个简单的 function ,它计算两个给定日期之间的天数。

It works well when both dates are valid.当两个日期都有效时,它工作得很好。 When a date is not valid I set the date to "0/0/0".当日期无效时,我将日期设置为“0/0/0”。

This is one my for loops:这是我的一个for循环:

for(int i = 0; i < date2.month - 1; i++)
    d2Days += monthDays[i];

Supposedly if a date is invalid the date2.month would be equal to 0 and the loop would not iterate at all but it does and it keeps on going indefinitely until i surpasses the size of the array and it seg faults.假设如果日期无效,则date2.month将等于 0,并且循环根本不会迭代,但它确实会继续下去,直到i超过数组的大小并出现故障。

在此处输入图像描述

You can see there i = 13 even when the month = 0即使月份 = 0,您也可以看到i = 13

Can someone explain why is that such behavior?有人可以解释为什么会这样吗?

I think @pmg nailed it in his comment above.我认为@pmg 在他上面的评论中指出了这一点。 If your date2.month member is unsigned, then when it is set to zero, decrementing it by one in the loop causes the integer overflow and returns INT_MAX .如果您的date2.month成员是无符号的,那么当它设置为零时,在循环中将其减一会导致 integer 溢出并返回INT_MAX When this occurs your loop condition will evaluate to true until you exceed the bounds of monthDays发生这种情况时,您的循环条件将评估为 true,直到您超出monthDays的范围

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

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