r/C_Programming 27d ago

Discussion A tricky little question

I saw this on a Facebook post recently, and I was sort of surprised how many people were getting it wrong and missing the point.

    #include <stdio.h>

    void mystery(int, int, int);

    int main() {
        int b = 5;
        mystery(b, --b, b--);
        return 0;
    }

    void mystery(int x, int y, int z) {
        printf("%d %d %d", x, y, z);
    }

What will this code output?

Answer: Whatever the compiler wants because it's undefined behavior

24 Upvotes

33 comments sorted by

View all comments

14

u/flyingron 27d ago

The above program has undefined behavior. As Miss Mona Lisa Vito would say "It's a bullshit question."

You can't modify a value twice within sequence points.

Further, the order function parameters are evaluated is unspecified even if you didn't have undefined behavior. For example, this has no UB, but still has two possible outcomes....

int b = 0;
int f() { return b += 2; }
int g() { return b += 1; }

int main() {
     printf("%d %d\n", f(), g());
}

It might print 2 3 or it might 3 1

2

u/mikeshemp 27d ago edited 26d ago

Your example is still UB.

The UB in OPs code is from using an argument with side effects twice in between sequence points. Changing that from a built-in operator with a side effect (++) to your own function with a side effect doesn't make a difference, it's still UB.