Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mr.iso

macrumors member
Original poster
Dec 29, 2003
47
0
Ok so I thought I understood all of this, but this is just plain weird.

First, for our usage, here's a dummy method:
Code:
- (void)dummy
{
    return;
}

Ok so to the problem... I am creating an NSStream delegate object, so I am implementing this method:
Code:
- (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:

Code:
- (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:
Code:
- (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...
 
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:
Code:
    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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.