C语言 C中'for'循环中的两个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7783284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Two variables in a 'for' loop in C
提问by liv2hak
I am writing some code where I need to use two variables in a forloop. Does the below code seem alright?
我正在编写一些代码,我需要在for循环中使用两个变量。下面的代码看起来没问题吗?
It does give me the expected result.
它确实给了我预期的结果。
for (loop_1 = offset,loop_2 = (offset + 2); loop_1 >= (offset - 190),loop_2 <= (190 + offset + 2); loop_1--,loop_2++)
{
if ( (*(uint8_t*)(in_payload + loop_1) == get_a1_byte(bitslip)) &&
((*(uint8_t*)(in_payload + loop_2) == get_a2_byte(bitslip)))
)
{
a1_count++;
}
}
But I am getting a compiler warning which says:
但是我收到了一个编译器警告,上面写着:
file.c:499:73: warning: left-hand operand of comma expression has no effect
file.c:499:73: 警告:逗号表达式的左操作数无效
What does this mean?
这是什么意思?
回答by Mat
The problem is the test condition:
问题是测试条件:
loop_1 >= (offset - 190),loop_2 <= (190 + offset + 2)
This does not check both parts. (Well, it does, but only the result of the second part is used.)
这不会检查两个部分。(嗯,确实如此,但只使用了第二部分的结果。)
Change it to
将其更改为
(loop_1 >= (offset - 190)) && (loop_2 <= (190 + offset + 2))
if you want both conditions to be checked.
如果你想检查这两个条件。
回答by caf
Mat is correct, but you should probably consider simplifying your code to:
Mat 是正确的,但您可能应该考虑将代码简化为:
for (i = 0; i <= 190; i++)
{
uint8_t *pl1 = (uint8_t *)(in_payload + offset - i);
uint8_t *pl2 = (uint8_t *)(in_payload + offset + i + 2);
if (*pl1 == get_a1_byte(bitslip) && *pl2 == get_a2_byte(bitslip))
{
a1_count++;
}
}
(You can obviously hoist the calculation of in_payload + offsetout of the loop too, but the optimiser will almost certainly do that for you).
(您显然也可以提升in_payload + offset循环外的计算,但优化器几乎肯定会为您做到这一点)。
回答by Jens Gustedt
For your semantically problems see caf's answer. First try to straight out your thoughts before starting to type.
对于您的语义问题,请参阅 caf 的答案。在开始打字之前,首先试着理清你的想法。
One misunderstanding is that you are mixing up two different concepts of C, initialization and assignment. Obviously in your code you are thinking in the lines of an initialization where the thing with the comma would work perfectly. So the next time you encounter a similar problem, just use local variables. These are valid constructs in C99, and a good thing to use, anyhow.
一种误解是您混淆了 C 的两个不同概念,初始化和赋值。显然,在您的代码中,您正在考虑初始化的行,其中带有逗号的东西可以完美地工作。所以下次遇到类似的问题,就用局部变量就好了。这些是 C99 中的有效构造,无论如何都是好用的。
You didn't give us the type of the variables but assuming size_tyour forstatement would look like
你没有给我们变量的类型,但假设size_t你的for语句看起来像
for (size_t loop_1 = offset, loop_2 = (offset + 2);
loop_1 >= (offset - 190) && loop_2 <= (190 + offset + 2);
loop_1--, loop_2++)

