Follow

"fun" C++ quiz time. what will this program print? (and why?)

Guess

@jeffrey close, but no. operator precedence with the minus!

Guess

3. The array only contains 3 vecs because (a,b,c) is just an expression that evals to c. -1[p].x is arr[0].x, which is the first value in the array, which is 3.

Guess

@jpab close, but not quite! That minus is subject to operator precedence rules...

Guess

@aras oh well, there had to be one more thing I was missing!

Guess

@aras I assume it must be -9. The bracket and comma initialisers just cancel down, p is pointing to the 2nd element, 1[p] is same as p[1] (ie. Now the 3rd element in arr) because magic, operator precedence puts the negate after the resolve, so x of the 3rd is 9, which is then negated?

Guess correction

@aras arg, looked it up, comma takes left side so -7

Guess correction

@mdiluz the thinking is correct, the answer nope :)

Guess correction

@aras oh. Oh no.

If *both* sets of commas cancel, and comma takes right side (got it right first time...) , then arr is actually (3,6,9),(12,15,18)... etc. Meaning we should have -21?

Guess correction

@aras or, well, not both "cancelling", the second set should aggregate? Don't know how to describe that, but C let's you initialize struct members in an array sequentially, so I'm sticking with -21

Guess correction

@aras I couldn't take the insanity and wrote it out. Looks right. Oh man. What a hellscape this language is.

:thinking:

Shouldn't it print 1 ?

arr[idx] is syntax sugar for *(arr + idx) so -1[p] == p[-1], and since p starts at the second element you should have the first then.

But does it compiles everywhere ?

Years ago, I had a similar situation with compiler warning about arithmetic operation on pointers, like "trying to access the *p value of the -1 array", but I don't remember well so I'll say 1, .x value of the 0th element 🙂

🤔

@Xipiryon hint 1: it does not index by -1, due to operation precedence.

Guess 2

Then -7 ? Since p already points to arr[1], then it's -((p+1)->x), so the 3rd element of the array 🙂

At least I hope operator precedence doesn't imply (-(p+1))->x, because it lools like an undefined behaviour then 😅

Oh and btw it's super nice of you to take the time to answer everyone !

Guess 2

@Xipiryon third element of the array, bingo! but that's not 7 or -7 :P

jeffrey@jeffrey@mastodon.gamedev.placeGuess

@aras -7? The tricky part being:

int x = -1[p].x;

which could be rewritten as:

int x = -p[1].x;

because ptr[index] == index[ptr] because pointer arithmetic, C, and the glory that is programming.