Switch Statement... what am I doing wrong here...

Discussion in 'iPhone/iPad Programming' started by mr.iso, Aug 9, 2011.

  1. macrumors member

    Joined:
    Dec 29, 2003
    #1
    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...
     
  2. macrumors 603

    Joined:
    Aug 9, 2009
    #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.
     
  3. thread starter macrumors member

    Joined:
    Dec 29, 2003
    #3
    Thanks!
     

Share This Page