Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading