Saturday, December 30, 2006

Increment Operators

is the C statement /*printf("%d, %d, %d\n", i,i++,++i)*/ a valid statement?
Think hard before arriving to any conclusions....

Well its not!!

firstly ehat do u expect the evalution order of functions a(), b() and c() in the following statement
printf("%d,%d,%d",a(),b(),c());

well by the C standards the behaviour is *unspecified* i.e. the arguments of a function may be evaluated in any order that may also be interleaved.... now this unspecified behaviour of evalution of the arguments may lead to undefined behaviour and hence the ambiguous result.

Secondly there is no sequence point between the different expressions(i, ++i, i++) and according to C standards modifying the value of an expression more than once between two sequence points leads to undefined behaviour and hence explains the ambiguous result.

try printf("%d", (i++,++i)); note: there is a sequence point in the expression.

No comments: