Home > Software design >  C Preprocessor, jumping out of #ifdef
C Preprocessor, jumping out of #ifdef

Time:11-17

I am currently learning C and I came across this question I can't find an answer to.

Can I jump out of a #ifdef without going through the #endif?
For example can I do this:

   char getOS( void ) {
       /* Returns the user Operating System
       */

       #ifdef _WIN32
           return 'w';

       #elif TARGET_OS_MAC
           return 'm';

       #elif __linux__
           return 'l';

       #else
           raiseError( "You cannot play on this OS", true );

       #endif

   }

CodePudding user response:

I believe you are misunderstanding the preprocessor a bit. Remember, the preprocessor runs before the compiler. So this function is going to look like one of the following when it gets to the compiler:

char getOS( void ) {
        return 'w';
}
char getOS( void ) {
        return 'm';
}
char getOS( void ) {
        return 'l';
}
char getOS( void ) {
        raiseError( "You cannot play on this OS", true );
}

... and these are all valid. Well I don't know what raiseError does, but if it isn't a macro that returns or exits, you will want to add an extra return to the end of the function for the #else branch.

The point is, none of that #if, #elif, etc is going to the compiler anyway, so you are never "jumping out". If you want to see for yourself, you can add a compiler option to only do preprocessing (and no compiling). I know for gcc, that option is -E.

CodePudding user response:

If by "jump out of", you mean cause the compiler to give an error, you can do that with the #error directive.

   #ifdef _WIN32
       return 'w';

   #elif TARGET_OS_MAC
       return 'm';

   #elif __linux__
       return 'l';

   #else
       #error "You cannot play on this OS"

   #endif

CodePudding user response:

You seem to be confusing preprocessor with runtime behavior: they are not the same.

The preprocessor runs before the actual compiler (at least conceptually; in practice they can very well be the same program of course). It affects the source that the compiler then sees.

You cannot "go through" the #endif, it's not there when the program runs. You will either have a return, or a call to raiseError().

  • Related