I read about 'side effect' from this website:
but still not understand why f = f++
considered unsafe ?
Can somebody explain?
I read about 'side effect' from this website:
but still not understand why f = f++
considered unsafe ?
Can somebody explain?
Asked yesterday: yesterday's instance of the same question, which is full of good insight for you, and you should follow along that discussion.
The problem is Sequence Points. There are two operations in this statment with no sequence point, so there is no defined order to the statement, is the assignment happening first or the increment?
Nothing says it's unsafe, it's just undefined, which means that different implementations may have different results or it may format your hard drive...
Using x
and x++
(or ++x
) within the same statement is undefined behaviour in C. The compiler is free to do whatever it wants: either increment x
before doing the assignment, or after that. Taking Ólafur's code, it might yield f == 5
or f == 6
, depending on your compiler.
The article at the (cleaned up) link you provided gives the answer. "C makes almost no promise that side effects will occur in a predictable order within a single expression." This means that you don't know in what order the = and the ++ will occur. It's compiler dependent.
If you follow the link from that article to the article about sequence points on the same site, you'll see that the compiler can optimize what and when it writes values back from the registers into the variables.
I support Arthur's answer in this respect. Though the implementation of the post incrementing operator i.e f++ is confusing, it is not considered unsafe. U should first understand how the compiler interprets it. whether it will increment f after it encounters a sentence termination (;) or immediately after using the value of f.
Pre-increment is always preffered as it takes one intruction less then Post-increment operator. So in for and while loops mostly pre-increment is preffered. Although there may be case where post increment will be handy but that will depend on program logic, say you want value of variable changes after certain execution of variable on previous value.
From the standard
6.5 (2) If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.74)
74) This paragraph renders undefined statement expressions such as
i = ++i + 1; a[i++] = i;
while allowing
i = i + 1; a[i] = i;