Question

   #ifndef _WINDOWS
   if(condition)
   {
     printf("to do in linux"); 
   }
   else
   #endif
   {
      printf("should work in both linux and windows...");
   }

My question: does this code work for both in linux and windows?

Was it helpful?

Solution 2

Since #ifdef, #ifndef and #endif are preprocessor's directives, these will be applied before the compilation starts, ignoring the following lines completely in case _WINDOWS is defined:

#ifndef _WINDOWS
if(condition)
{
  printf("to do in linux"); 
}
else
#endif

Note that the condition will be evaluated only in case it is not on Windows.

On Windows, there will be nothing but the following nested anonymous scope:

{
   printf("should work in both linux and windows...");
}

OTHER TIPS

You have more logic than you need - you can just do this:

#ifndef _WINDOWS
     printf("to do in Linux"); 
     // ...
#endif
     printf("to do in both Linux and Windows");
     // ...

Actually, the ELSE statement won't run on Linux, because the compiled source code would be:

if(true)
{
   printf("to do in linux");
}
else
{
   printf("should work in both linux and windows and i have multiple statements in this else bolck");
}

And keep in mind that instead of true in C we have non-zero values, so if(1) for example (or you need a proper define for true keyword, or just `#include like @JonathanLeffler suggests).

But you could have definitely tried it with different defines in your code.

It won't work on WINDOWS

Use this :

   #ifndef _WINDOWS

    printf("to do in linux"); 
    //...
    #else
    printf("should work in both linux and windows and i have multiple statements in this else bolck");
  //...Other blocks of code
 #endif
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top