0

Please test out this code:

#include <stdio.h>

unsigned f(unsigned x) {
    unsigned res;
    asm(
        "movl $4, %0\n\t"
        "testl %1, %1\n\t"
        "cmovnel %1, %0\n\t"
        : "=r"(res)
        : "r"(x)
        : "cc"
    );
    return res;
}

int main() {
    for (unsigned i = 0; i < 10; ++ i)
        printf("%u, ", f(i));
    return 0;
}

As you see, the function f(x) is basically:

unsigned f(unsigned x) {
    return f ? f : 4;
}

The problem is that sometimes it returns the correct result, sometimes it does not.

If you run the above code on cpp.sh, you can get the intended behavior. It prints 4, 1, 2, 3 ...

But if you run it on programiz online compiler, you will get 4, 4, 4, 4 ...

When I ran it locally, I got 4, 4, 4, 4 ...

What is the problem with this piece of code? Thank you.

Jester
  • 56,577
  • 4
  • 81
  • 125
RabidBear
  • 182
  • 1
  • 6
  • 3
    The usual case of writing output before consuming the input so if the compiler picks the same register it won't work. Use an early clobber modifier. – Jester Apr 19 '22 at 18:43
  • 1
    @Jester Did not know about that. Tested the modified version out and it works. Thank you! – RabidBear Apr 19 '22 at 19:06

0 Answers0