Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters in for loop, missing first one?

Tags:

c

for-loop

I don't understand the for loop here. Could someone explain it to me? Normally. This one is missing a first statement and the second one says something different.

/* strcmp: return <0 if s<t, 0 if s==t, >0 if s>t */
int strcmp(char *s, char *t)
{
    for ( ; *s == *t; s++, t++)
        if (*s == '\0')
            return 0;
    return *s - *t;
}
like image 359
AlldaRage Avatar asked Dec 30 '25 13:12

AlldaRage


2 Answers

According to C standard $6.8.5.3. For the following statement:

 `for(clause_1;expression-2;expession-3) statement` 

Both clause-1 and expression-3 can be omitted, and expression-2 could be replaced by an non-zero constant.

Compiler's action

To answer your question fundamentally, let's look into how compiler handle your code.

For the for loop stmt in your code

From a compiler's aspect, the loop will finally be transformed into instruction sequence end with condition backward jump instruction as bellow.

   ...
   INST1
   INST2
   COND_JMP LABEL2
LABEL1:
   INST3
   INST4
   INST5
   COND_JMP LABEL1

LABEL2:
   ...

for's clause-1 will be put before the LABEL1, such as INST1 and INST2, therefore it is OK to omit such code. Since developer could also put such operations before the for statement.

expression 3 will be put into the loop body (instruction sequence between LABEL1 and COND_JMP LABEL1), therefore epression 3 code could also be put into the loop body directly in c code, that is why expression 3 could also be omitted.

expression 2 will be the condition used by the COND_JMP instruction, therefore if omitted directly, that means compiler will not insert COND_JMP outside the loop body, this will make for statement meaningless, that is why expression 2 could only be replaced by non-zero constant. When replace by non-zero constant that means always true in C, and then the loop will be an infinite loop.

for the comma of your for stmt expression-3

According to C standard 6.5.17, For he comma expression as following.

  expression, expression-2, expression-3..., expression-last

Here the expression could be an normal expression, or an assignment expression.

For such comma expressions, compiler will generate code which will evaluate all these expressions, and return the type and value of last one as the comma exression's return type and value.

like image 67
Kun Ling Avatar answered Jan 01 '26 03:01

Kun Ling


The initialization statement is empty. This means "no initialization action".

like image 31
Daniel Daranas Avatar answered Jan 01 '26 03:01

Daniel Daranas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!