vendredi 7 janvier 2022

How to understand sequenced-before and reorder?

Sequenced-before is defined in C++ standard that

If A is sequenced before B, then evaluation of A will be complete before evaluation of B begins

And there is a long list of rules about when A is sequenced-before B.

However, from this list I find a full expression is sequenced before the next full expression. Since an entire expression statement is a full expression, so in the following codes, 3/4/5 are full expressions while 1/2 are not(they are declaration statements).

int main(){
    int a = 1; // 1
    int b = 2; // 2
    a = 10; // 3 
    b = 20; // 4
    printf("%d %d", a, b); // 5
}

So, according to definition of sequenced-before, can compiler/CPU reorder 3/4?

I have two answers:

  1. No, they can't

    This is because 3 is sequenced-before 4, so 3 must be executed before 4.

  2. Yes, the can

    According to the as-if rule, C++ allows any and all code transformations that do not change the observable behavior of the program. Since the order of 3 and 4 does not matter, so compiler/CPU have every reason to reorder, according to as-if rule.

Seems I get a contradiction here.

UPDATE

How about

int main(){
    int a = 1; // 1
    int b = 2; // 2
    a = random_int(); // 3 
    b = random_int(); // 4
    printf("%d %d", a, b); // 5
}

Aucun commentaire:

Enregistrer un commentaire