1

Let's say you have the code as follows:

float arr[] = {
    0.0f,
    1.0f,
    62.0f,
    400.0f
};

Then I print this out as follows:

printf("%lu\n", sizeof(0[arr]));

Why does it return 4, and what is happening here?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
sentrix
  • 39
  • 4
  • 1
    `x[i]` is a syntactic sugar for `*(x+i)`, which is the same as `*(i+x)` which is in turn `i[x]`. There are should be a bunch of duplicates for this... – Eugene Sh. Jan 14 '22 at 19:36
  • @EugeneSh.: Would you expect a beginning student to know what “X is syntactic sugar for Y” means? That’s not a defined term. Is there something in colloquial language you think they would relate it to? Would it have any more meaning for them than if you said “X is parsing maple syrup for Y?” – Eric Postpischil Jan 14 '22 at 19:52
  • 1
    Note that the correct `printf` directive for a `size_t` argument (such as the result of the `sizeof` operator) is `%zu`. The `%lu` appearing in the example code may happen to be equivalent on some platforms, but it is quite wrong on others. – John Bollinger Jan 14 '22 at 19:54
  • @EugeneSh. I come from java development, where to my knowledge, something like this doesn't exist. – sentrix Jan 14 '22 at 20:18

1 Answers1

1

From the C Standard (6.5.2.1 Array subscripting)

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

So this expression 0[arr] is equivalent to the expression arr[0].

The only difference is relative to how the subscript operator is defined in the C grammar.

It is defined like

postfix-expression [ expression ]

So for example

++i[arr] is not the same as arr[++i]. The first expression is equivalent to ++( i[arr] ). While this expression i++[arr] is equivalent to arr[i++].

Here is a demonstration program.

#include <stdio.h>

int main( void )
{
    int arr[] = { 10, 20 };
    size_t i = 0;

    printf( "++i[arr] = %d\n", ++i[arr] );

    i = 0;

    printf( "arr[++i] = %d\n", arr[++i] );
    
    putchar( '\n' );

    i = 0;
    arr[0] = 10;

    printf( "i++[arr] = %d\n", i++[arr] );

    i = 0;

    printf( "arr[i++] = %d\n", arr[i++] );
}

The program output is

++i[arr] = 11
arr[++i] = 20

i++[arr] = 10
arr[i++] = 10
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335