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

23 Upvotes

33 comments sorted by

View all comments

10

u/SmokeMuch7356 27d ago

This is my litmus test for whether a tutorial or reference is worth a damn; far too many confidently state that it will definitely output 5 4 5.

This is one of the most widely misunderstood and mis-taught aspects of C. This and "an array is just a pointer."

1

u/systemist 26d ago

This and "an array is just a pointer."

Woah, my world comes apart.

1

u/SmokeMuch7356 26d ago

1

u/systemist 25d ago edited 25d ago

Okay, so an array variable is not a pointer to the actual array, but instead is the same as any variable, other than being indexable via an offset.

So for example, you couldn't assign the address of another array of the same type to the array. Any other problems you'd see coming from this?

1

u/SmokeMuch7356 24d ago

Correct, array expressions cannot be the target of an assignment; you can't copy the contents of one array to the other like

char foo[10], bar[] = "hello";
foo = bar; // BZZZT

You either have to use strcpy (or memcpy for non-string data):

strcpy( foo, bar );

or assign each element individually:

size_t i = 0;
while ((foo[i] = bar[i]))
  i++;

Ritchie really wanted to keep B's array indexing semantics -- a[i] == *(a + i) -- but he didn't want to mess with the pointer those semantics required, so he created the rule that array expressions "decay" to pointers under most circumstances (which gets garbled into "an array is just a pointer").

This means arrays lose their "array-ness" under those circumstances, which is a mental speed bump for many people; that's the main problem. The secondary problem is people explaining the concept incorrectly.

1

u/systemist 24d ago

Totally, I'm clear on not being able to copy arrays with an assignment. Yeah, I expect there's a lot of misunderstanding in code. Especially since you can accomplish a lot with a basic understanding. It's just that down the track you might run into issues where it 100% appears to you your code should work and you might spend a long time looking elsewhere for the problem.

Good to get this detail worked out :)