2

I'm stuck with a C program I'm currently writing in Xcode. After having worked on it for several hours, Xcode suddenly started complaining with the "expected expression" message:

  switch(cmd) {

    case 'S':
      state = sstart;
      accpos = accmax = varnum = 0;
      inquote = inddstar = false;
      break;

    case 'L':
      char c;   // *** expected expression
      int i = 0;
      bool processed;

      while( (c = buff[i++]) != '\0') {
        acc[accmax++] = c;

After which Xcode complains that the variable c is not defined whenever c is used.

I have tried "show invisibles" in Xcode to no avail. Compiling the program manually with clang or gcc gives the same error message.

After the preprocessor step, this part of the code looks as follows (obtained with clang -E):

  switch(cmd) {

    case 'S':
      state = sstart;
      accpos = accmax = varnum = 0;
      inquote = inddstar = 0;
      break;

    case 'L':
      char c;
      int i = 0;
      _Bool processed;

      while( (c = buff[i++]) != '\0') {
        acc[accmax++] = c;

so nothing interesting either.

Any ideas? I wrote my last C program 23 years ago so I might have missed something...

uselpa
  • 18,732
  • 2
  • 34
  • 52

1 Answers1

10

You would need to enclose that case in braces. In C you are required to enclose a switch-case in braces if there is a variable initialization. It should be as follows:

case 'L': {
  // ... your code.
  break;
}

Even though your compiler may allow for you to declare variables inside a swith-case, it's not a good idea to do so. It's likely that you can replace that case with a helper function.

See this for a lower level explanation.

Community
  • 1
  • 1
Jacob Pollack
  • 3,703
  • 1
  • 17
  • 39
  • Funny thing is, it worked without braces for quite some time, but after some edit it started complaining. – uselpa Aug 13 '13 at 20:29