Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two variables in a 'for' loop in C

Tags:

c

for-loop

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?

like image 833
liv2hak Avatar asked Oct 16 '11 08:10

liv2hak


People also ask

Can you have two variables in a for loop C?

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.

Can you have two arguments in a for loop?

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.

Can you increment two variables in for loop C?

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.

Can you declare a variable in a for loop in C?

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.


2 Answers

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.

like image 54
Mat Avatar answered Oct 02 '22 18:10

Mat


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).

like image 29
caf Avatar answered Oct 02 '22 18:10

caf