Side_effect: (++x + y*x + y*x) != (y*x + ++x + y*x) ?

This is a discussion on Side_effect: (++x + y*x + y*x) != (y*x + ++x + y*x) ? within the C Programming forums, part of the General Programming Boards category; rather annoying it is looking at this x + ++x; to simplify try the following; (for constant increments) int y ...

  1. #16
    Comment your source code! Lynux-Penguin's Avatar
    Join Date
    Apr 2002
    Posts
    533
    rather annoying it is looking at this
    x + ++x;
    to simplify try the following;
    (for constant increments)
    int y = x++;
    this gives me an idea, if I start a company, I am going to make a new C language called ++C
    Asking the right question is sometimes more important than knowing the answer.
    Please read the FAQ
    C Reference Card (A MUST!)
    Pointers and Memory
    The Essentials
    CString lib

  2. #17
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,767
    > I have enough knowledge to sure that the order of the execute of this expression.
    No you don't - that's the whole point of this exercise.

    Sure, for a simple example, for a given compiler, you can work it out, but no one knows which order ANY expression will be evaluated, for ANY compiler.

    If you could predict the order, then the complex expression which you have would evaluate in the same way no matter where you write it (but it doesn't, and you can't).

    But you know that this isn't the case - you have the same expression in different environments (one assigment, one function call parameter), and you're getting different answers.

    Now something's got to give here.
    You are assuming that an expression always evaluates its operands in the same order. This is NOT TRUE (you know it's not true, you've got different answers).

    Now, this difference in order of evaluation of operands DOES NOT matter when the operands are free of side effects. It only becomes apparent that something different is going on when you have multiple side effects. As we've said before, such expressions are by definition undefined, so there is no point whatsoever from trying to guess what they do, and absolutely no point in using them in real code.

    > If the key is at register as you said, we have the same result in both expression - in and out of the printf function. Do you agree with me?
    No, and neither does your compiler

    > why there is the difference of evaluetion an expression in and out the printf function
    At a guess, maybe the call has already used one register, which means there is one less free to evaluate the expression. As a result, different code will be generated.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21