Thread: Evaluationof expressions

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    22

    Evaluationof expressions

    Hi all

    I'm just re-reading K&R and there's something I don't understand, Appendix A7. Expressions:
    "The precedence and associativity of operators is fully specified, but the order of evaluation of expressions is, with certain exceptions, undefined, even if the subexpressions involve side effects. That is, unless the definition of an operator guarantees that its operands are evaluated in a particular order, the implementation is free to evaluate operands in any order, or even interleave their evaluation."
    Looking at this:
    Code:
    int a = 5;
    int b = ++a;
    How can I be sure that 'b' takes the value of 6, if the evaluation of the expression '++a' could be interleaved?...I think I misunderstand something here, but I don't see what. I also searched on Google and on the board, read a lot, but it is still not really clear :/
    Hopefully somebody can explain me

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Statements are not interleaved - http://c-faq.com/expr/seqpoints.html

    What K&R are referring to would be something like this
    Code:
    a = f() + g() * h() - i();
    If you consider only precedence, you might conclude that g() and h() would be called first. This is simply not the case. Nor could you assume that g() and h() would be called consecutively.

    This is really important since it makes all such multiple side effect expressions such as this as being undefined.
    b = a++ + ++a;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2007
    Posts
    22
    Hm...ok, that makes sense now. Many thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stack that evaluates postfix expressions
    By killmequick in forum C Programming
    Replies: 7
    Last Post: 10-01-2008, 06:23 PM
  2. Regular expressions [Boost]
    By Desolation in forum C++ Programming
    Replies: 8
    Last Post: 12-30-2006, 10:10 PM
  3. Help please: regular expressions in C++
    By reivaj7999 in forum C++ Programming
    Replies: 3
    Last Post: 08-24-2005, 01:11 AM
  4. Regular expressions
    By jverkoey in forum A Brief History of Cprogramming.com
    Replies: 9
    Last Post: 01-23-2005, 09:36 PM
  5. Prefix Expressions
    By mannyginda2g in forum C++ Programming
    Replies: 4
    Last Post: 03-19-2004, 01:30 AM