Thread: Using switch statements in function-like macros

  1. #1
    Registered User
    Join Date
    Jul 2009

    Using switch statements in function-like macros

    Maybe someone out there can help me understand my problem. I'm trying to use a switch statement in a function-like macro, but I keep getting the following error:

    error: expected expression before ‘switch’

    Here's some example code of what I'm doing. It's not fancy but I'm just trying to get the concept down:

    #include <stdio.h>
    #include <stdlib.h>
    #define MACRO_SUCCESS 1
    #define MACRO_FAILURE 0
    #define check_error(error) \
    ( switch (error) \
      {              \
        case 1:  return MACRO_SUCCESS;  \
        case 2:  return MACRO_FAILURE;  \
      }              \
    int main (int argc, char *argv[])
    	printf("error flag = %d\n\r", check_error(2));
    	printf("error flag = %d\n\r", check_error(1));
    	return 0;

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    You can't put a switch statement inside a printf statement. (Remember that macros just do plain old text substitution.) You can use a real function if you want. If for some pedagogical reason you are required to use a macro, you can use ?: in this case.

  3. #3
    Registered User BlackOps's Avatar
    Join Date
    Jul 2009
    or maybe u could do something like this:

    #define MACRO_SUCCESS 1
    #define MACRO_FAILURE 0
    #define check_error2(error) int flag; \
    switch (error)    \
    { \
    case 1: {flag = MACRO_SUCCESS; break; } \
    case 2: { flag = MACRO_FAILURE; break; }   \
    } \
    int y = 1;
    printf("error flag = %d\n", flag);

  4. #4
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Portland, OR
    The problem here is that the error values being used aren't equal to the MACRO_XXX values. If they were equal, there would be no need for this silly thing.

    If there's some legitimate reason you have to map these values, I'd probably just use a lookup table.
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. C++ compilation issues
    By Rupan in forum C++ Programming
    Replies: 1
    Last Post: 08-22-2005, 05:45 AM
  3. Replies: 4
    Last Post: 11-23-2003, 07:15 AM
  4. Replies: 5
    Last Post: 02-08-2003, 07:42 PM
  5. Replies: 2
    Last Post: 05-10-2002, 04:16 PM