Fundamental C- Side Effects, Sequence Points And Lazy Evaluation |
Written by Harry Fairhead | ||||
Monday, 11 February 2019 | ||||
Page 3 of 3
So far sequence points simply tell you when you can expect side effects to be complete, but they don’t help with the problem of: i=i++; The sequence point is at the end of the expression and it still isn’t clear whether the side effects occurred as assignment then increment, or increment then assignment. To deal with this the C11 standard also introduced two conditions that have to be satisfied to make an expression legal: Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. These two rules make i=i++ undefined as the variable has its value changed more than once. The second condition also makes expressions such as: array[i]=i++; undefined as, even though i is only modified once, its original value is used to determine where the result is stored and not just what the result is. Many programmers find the C sequence rules difficult to understand and apply, but this really isn’t the problem. If your code causes you to contemplate the role of a sequence point or the conditions that apply then you are probably writing expressions that should not be written. It really shouldn’t need a rule to convince you that writing: i=i++; is a bad idea. In general, relying on side effects isn’t a good idea unless their role and meaning is very simple and very clear. If an expression has you wondering exactly what it means then it will make you or some other programmer wonder what it means the next time you see it, even if you manage to work out its meaning this time around. Summary Of Chapter
Related ArticlesRemote C/C++ Development With NetBeans Getting Started With C/C++ On The Micro:bit To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
||||
Last Updated ( Sunday, 17 March 2019 ) |