Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of this C statement well defined?

The title is a bit vague as I don't really know how to define this question.

It has to do with the following code:

for (match         = root,
     m_matchBase   = match->requestedBase,
     m_matchLength = match->length;

     match != NULL;

     match         = match->next,
     m_matchBase   = match->requestedBase,
     m_matchLength = match->length)
{
    if (m_matchBase <= m_base && m_matchBase + m_matchLength > m_base)
        break;
    // other stuff...
}

Are the statements in the for loop guaranteed to run sequentially?

For example, is m_matchBase = match->requestedBase guaranteed to run after match = match->next?

like image 408
Jimmy Lu Avatar asked Jan 17 '14 19:01

Jimmy Lu


4 Answers

Yes, the comma operator (which is what is being used here) will sequence the operations. This means that your loop will quite likely crash when match->next becomes null.

like image 96
Mark B Avatar answered Nov 04 '22 04:11

Mark B


The expressions will be evaluated from left to right and there will be a sequence point after each evaluation. In C the grammar for a for statement without a declaration from the draft C99 standard section 6.8.5 Iteration statements is:

for ( expressionopt ; expressionopt ; expressionopt ) statement

So the , in each set of expressions will be a comma operator as opposed to just a separator, which means the assignments will be evaluated from left to right. This is covered in section 6.5.17 Comma operator which says:

The left operand of a comma operator is evaluated as a void expression; there is a sequence point after its evaluation. Then the right operand is evaluated; the result has its type and value

Whether this is maintainable code is another question, it is important to note that when match>next returns NULL you will be invoking undefined behavior in subsequent sub-expressions. Which probably goes some way to demonstrate this is a poor choice in style since it is easy to miss and hard to check in the current form.

like image 35
Shafik Yaghmour Avatar answered Nov 04 '22 04:11

Shafik Yaghmour


Yes, see c++11 standard (5.18):

A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded- value expression

like image 20
tumdum Avatar answered Nov 04 '22 04:11

tumdum


Yes.

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

The && operator also has a sequence point.

like image 42
Samuel Edwin Ward Avatar answered Nov 04 '22 04:11

Samuel Edwin Ward