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.

phuclv
  • 37,963
  • 15
  • 156
  • 475
Naval Kishore
  • 115
  • 1
  • 7

1 Answers1

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])?

phuclv
  • 37,963
  • 15
  • 156
  • 475