PDA

View Full Version : Switch Statement... what am I doing wrong here...




mr.iso
Aug 9, 2011, 10:58 AM
Ok so I thought I understood all of this, but this is just plain weird.

First, for our usage, here's a dummy method:

- (void)dummy
{
return;
}


Ok so to the problem... I am creating an NSStream delegate object, so I am implementing this method:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode

Here is what I have so far, it's not much at all, and I'm already having a problem with the switch statement:

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch(eventCode)
{
case NSStreamEventHasBytesAvailable:
uint8_t buffer[1024];
break;
}
}

I'm getting an error on the line with uint8_t buffer[1024]; The error is "Expected expression".... that's it, nothing more than that. That is the full error!

If I do this, the error goes away:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch(eventCode)
{
case NSStreamEventHasBytesAvailable:
[self dummy];
uint8_t buffer[1024];
break;
}
}

Anyone have any ideas why this is happening? I am using the Xcode beta, so maybe that's an issue with the beta? I tried reverting to the non-beta version but I apparently can't. It still says xcode 4.2...



chown33
Aug 9, 2011, 11:35 AM
Short answer: It's an artifact of the switch statement's syntax.

You can look up the long answer in the C standard or its BNF for the grueling details.

Or google search terms:
c switch case declare variables
and read the entries from stackoverflow.com.


FWIW, you can solve the problem using { }, such as:
switch(eventCode)
{
case NSStreamEventHasBytesAvailable:
{
uint8_t buffer[1024];
break;
}
}

This always works, because anywhere you can have a statement, you can put a block. And the beginning of any block can declare variables (scoped to the block), even in early C.

mr.iso
Aug 9, 2011, 11:48 AM
Thanks!