-3

Following a suggestion in a comment here, I'm trying to understand how does Compiler Explorer work. My input is the following piece of code:

int main() {
    double x,y,x0,y0,x1,y1;
    x = 10;
    y = 10;
    x0 = 5;
    y0 = 5;
    x1 = 15;
    y1 = 15;
    if (x > x0 && x < x1 && y > y0 && y < y1)
        return 1;
    return 0;
}

The result is:

    mov     eax, 1
    ret

I have learned the basics of assembler many years ago, but I don't know if, or how, this makes any sense. Does it? (What I was trying to find is if adding an "else" between the two returns would have any difference in performance. According to this site, it doesn't. But am I getting it right?)

Jongware
  • 22,200
  • 8
  • 54
  • 100
Rodrigo
  • 4,706
  • 6
  • 51
  • 94
  • 7
    It makes perfect sense. No matter how many times you run this code, the end result is always 1. The compiler is smart enough to figure it out. So that's what you get. What exactly is so unclear, about this? – Sam Varshavchik Dec 01 '18 at 02:21
  • Your variables will always have the same values on every run. The compiler is seeing this and is evaluating the entire `main` function for you, which, it appears, will always return 1. Try disabling optimizations or letting your variables' values be given by the user at runtime. – alter_igel Dec 01 '18 at 02:21
  • 1
    [What exactly is the "as-if" rule?](https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule) – Swordfish Dec 01 '18 at 02:22
  • If you don't like efficient code, maybe you should learn to use `volatile`! – curiousguy Dec 01 '18 at 02:31
  • Yup, this question isn't worth keeping. Constant-propagation is one of the most important compiler optimizations, but also fairly easy and straightforward. See [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116) for a Q&A which suggests writing functions with args instead of of constants, like you did in your update. – Peter Cordes Dec 01 '18 at 03:00
  • @PeterCordes "You cannot delete this question..." – Rodrigo Dec 01 '18 at 09:56
  • @Rodrigo: Ah right, because it has an upvoted answer. You'd have to ask Pete Becker to delete his answer, or just leave it alone and hope it doesn't attract any further attention/downvotes. – Peter Cordes Dec 01 '18 at 10:17

1 Answers1

3

The condition is true. The compiler optimizes it out; it generates code for return 1;.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Right, I was doing it wrong. Now I think I'd better delete the question, though I'll edit it first and see what you say. – Rodrigo Dec 01 '18 at 02:28
  • I was thinking about deleting this question. But I can't because of your answer. What do you say? – Rodrigo Dec 01 '18 at 09:57