Retro C++ quiz #56

Given the following in C and C++ (assume correct header is included):

int main(void) {
int n = sizeof(0)["abcdefghij"];
printf("%d\n",n);
}

Without checking, assuming LP64, what’s the result:

C | C++
=========
A. 1 | 1
B. 101 | 101
C. 1 | 101
D. 101 | 1

#Cplusplus
#Cpppolls
#Programming

A
20%
B
46.7%
C
26.7%
D
6.7%
Poll ended at .

The answer is A, surprise! This works the same in C and C++ I bet you were not expecting that.

You may be surprised to learn that sizeof works with both a parenthesized type-id or a unary expression see [expr.unary]p1 https://eel.is/c++draft/expr.unary#general-1

We don’t have a parenthesized type-id so it must be a unary expression we are working with.

You may recognize it if we flip it around a bit:

"abcdefghij”[(0)]

Yup, just array indexing, [expr.sub]p1 http://eel.is/c++draft/expr.sub#1

Which says:

“The expression E1[E2] is identical (by definition) to *((E1)+(E2))”

So we end up with size of char which is 1 by [expr.sizeof]p1 http://eel.is/c++draft/expr.sizeof#1

[expr.unary]

@shafik I really don't know about C but I'm guessing it's like C++? Never used it beyond a couple isolated occasions

@shafik

That is a tricky one. who thinks about associativity and precedence of operators when seeing sizeof.