I am writing some code where I need to use two variables in a for
loop. Does the below code seem alright?
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
What does this mean?
Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.
With two arguments in the range function, the sequence starts at the first value and ends one before the second argument. Programmers use x or i as a stepper variable.
Yes, C Compiler allows us to define Multiple Initializations and Increments in the “for” loop. The image below is the program for Multiple Initializations and Increments. In the above program, two variable i and j has been initialized and incremented. A comma has separated each initialization and incrementation.
It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope.
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.
Mat is correct, but you should probably consider simplifying your code to:
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 + offset
out of the loop too, but the optimiser will almost certainly do that for you).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With