2

I've seen an example showing as

int n = sizeof(0)["abcdefghij"];
cout<<n;

What does that thing in square brackets mean? I've read somewhere that (0)["abc"] is equivalent to ("abc")[0]. Meaning the above expression is simply

n = sizeof("abcdefghij")[0]; 

i.e. the first element.

7
  • "abcdefghij" is just const char [N], i.e. an array, so it's equivalent to sizeof("abcdefghij"[0]) because sizeof has higher precedence than []
    – phuclv
    Commented Feb 7, 2021 at 6:34
  • @phuclv - You had correct initially, pre-edit. It's not sizeof("..."[0]). Commented Feb 7, 2021 at 6:40
  • 1
    Naval, this example has a pretty poor practical value, if any at all. It may be a cool puzzle, but is not indicative of any real world construct. Commented Feb 7, 2021 at 6:43
  • sizeof is not a function: edit your title. Commented Feb 7, 2021 at 6:51
  • @StoryTeller-UnslanderMonica the precedence is wrong but the result is actually correct. I've checked it
    – phuclv
    Commented Feb 7, 2021 at 6:58

1 Answer 1

6

First, sizeof is not a function but an operator

sizeof(0)["abcdefghij"] can be parsed as either

  • sizeof( (0)["abcdefghij"] ), or
  • ( sizeof(0) )["abcdefghij"]

Since sizeof has lower precedence than [], the former will take place

(0)["abcdefghij"] is equivalent to "abcdefghij"[0] which is just 'a', so the whole thing is the same as sizeof('a') which is 1 in C++

Demo on GodBolt, ideone

If you replace sizeof(0) with sizeof(int) then the same thing happens, but now (int)["abcdefghij"] is invalid so it should result in a compilation fail. Most compilers report an error as expected that except ICC so it looks like that's an ICC bug which chooses (sizeof(int))["abcdefghij"] over sizeof((int)["abcdefghij"]) just because the latter is invalid

Related: Why does sizeof(my_arr)[0] compile and equal sizeof(my_arr[0])?

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.