Table test result is not the same as compiled?

Asked

Viewed 146 times

-2

The code below when executed returns the result to m = 0, but doing the test table the result should be -2.

I can’t prove the 0as a result unless the variable t++ when in (t * t++), only at this moment and only she, acquired the value 4, which is something also strange. I tested in PHP and C.

 int t = 3;
 int p = -5;
 int q = 1;
 int m = (q * p + (t * t++)- (t + q))-2;
  • You will "have fun" even more when you start debugging and realize that in ($t * $t++) the "four" that Voce said is the... on the left..! and the three on the right :D (for that very reason, in PHP it is usually more interesting to use ++$i than $i++ in a loop for, where possible, to avoid creating an unnecessary reference)

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

  • I didn’t try to debug Bacco, but I will.

1 answer

2


Obviously your table test is wrong. Table tests need to simulate what the computer does and not what you want it to do. I don’t even know if it’s the table test case, just do the simple math.

Maybe you’re talking about undefined behavior in C which is to exchange the value of t in progress in the expression. Take the ++ and will give the result you expect. If you need it you need to see where you want to go and assemble the expression in another way. Never use an operator that causes side effect on the variable in the middle of an expression.

In PHP may be different, in other compiler version C or other platform may be different.

#include <stdio.h>

int main(void) {
    int t = 3;
    int p = -5;
    int q = 1;
    int m = (q * p + (t * t) - (t + q)) - 2; 
    int n = (q * p + (t * ++t) - (t + q)) - 2;    
    t = 3;
    int o = (q * p + (t * t++) - (t + q)) - 2;    
    printf("%d, %d, %d", m, n, o);
}

Behold working in the ideone. And not working in the repl it.. Also put on the Github for future reference.

  • Ola Maniero, thank you for sharing your knowledge, I put the same code in Java that you assigned -3 to "m". I believe that all languages should make the same attribution value. And it’s interesting the term that used "side effect", apparently it can be dangerous how to use this increment operator.

  • Yes and yes. :) ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.