简体   繁体   中英

sequence point and side effects

According to sequence point definition, sequence points are " specified points in the execution sequence called sequence points, all side effects of previous evaluations are guaranteed to be complete "

So in the below program, all side effects of ++ operator must have been performed before going to second part of && operator, ie, i should be incremented to 1 as && is a sequence point.

#include<stdio.h>

int main()
{
    int i=0,a;
    a=i++&&1;
    printf("%d",a);
    getchar();
    return 0;
}

Expected output:

1 ( 1&&1=1 )

actual output :

0

Why doesn't i increment before 2nd part?

Using the ternary operator also gives same output:

#include<stdio.h>

int main()
{
    int i=0,a;
    a=(i++)?1:0;

    printf("%d",a);
    getchar();
    return 0;
}

The ternary operator is also a sequence point. So shouldn't this give output 1 instead of 0?

i++

Evaluates to previous value of i .

As a side effect value of i is incremented by 1 .

So yes the sequence point is there but the expression i++ evaluates to 0 (though value of i is 1 at the same time)

For the expected results use ++i instead of i++ .

From 6.5.2.4 Postfix increment and decrement operators in C11 specs:

The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The value computation of the result is sequenced before the side effect of updating the stored value of the operand. With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation. Postfix ++ on an object with atomic type is a read-modify-write operation with memory_order_seq_cst memory order semantics. 98 )

98) Where a pointer to an atomic object can be formed and E has integer type, E++ is equivalent to the following code sequence where T is the type of E:

 T *addr = &E; T old = *addr; T new; do { new = old + 1; } while (!atomic_compare_exchange_strong(addr, &old, new)); 

with old being the result of the operation. Special care must be taken if E has floating type; see 6.5.16.2.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM