Search code examples
arrayscvariable-length-array

Why is this C array giving the "Expected Expression" error?


learning the C programming language and reading the documentation with Xcode 13.2 open and a Command-Line Tool project in front of me.
Reading this, in the Declarations/Arrays/Variable Length Arrays section:

{
   int n = 1;
label:
   int a[n]; // re-allocated 10 times, each with a different size
   printf("The array has %zu elements\n", sizeof a / sizeof *a);
   if (n++ < 10) goto label; // leaving the scope of a VLA ends its lifetime
}

And copying it in Xcode, inside the main function, it just gives me the "Expected expression" error next to the int a[n]; line. I tried to put this into a separate function but this was not the solution.
What is going wrong here?
Thank you


Solution

  • The only thing that can follow a label is a statement, and a declaration is not a statement. You'll have to wrap the code following the label in a block somehow:

    #include <stdio.h>
    
    int main( void )
    {
      int n = 1;
    label:
       do {
        int a[n];
    
        printf( "The array has %zu elements\n", sizeof a / sizeof a[0] );
        if ( ++n < 10 ) goto label;
      } while ( 0 );
    
      return 0;
    }
    

    Now the results should be what you expect:

    $ ./vla
    The array has 1 elements
    The array has 2 elements
    The array has 3 elements
    The array has 4 elements
    The array has 5 elements
    The array has 6 elements
    The array has 7 elements
    The array has 8 elements
    The array has 9 elements
    

    For the love of God don't do this.

    EDIT

    Using just an empty statement after the label:

    #include <stdio.h>
    
    int main( void )
    {
      int n = 1;
    label:
      ;
      int a[n];
    
      printf( "The array has %zu elements\n", sizeof a / sizeof a[0] );
      if ( ++n < 10 ) goto label;    
      return 0;
    }