C - ifdef



 ifdef

Learn C - C tutorial - Ifdef - C examples - C programs

C - ifdef - #ifdef - Definition and Usage

  • If the value of expression is true, then the code that immediately follows the command will be compiled.
  • “#ifdef” directive checks whether the particular macro is defined or not.
C Preprocessors #ifdef

C Syntax

(#ifdef identifier newline );

Syntax explanation:

  • #ifdef directive checks whether the identifier is currently defined.
  • Identifiers can be defined by a #define directive or on the command line.
  • If such identifiers have not been subsequently undefined, they are considered currently defined.

#else:

  • If #ifdef directive is defined, “If” clause statements are included in source file. Otherwise, “else” clause statements are included in source file for compilation and execution..

C Syntax

#endif newline;

#endif:

  • #endif always matches the nearest #ifdef (or #ifndef, or #if).
  • Also, we cannot start a conditional group in one file and end it in another.
  • The number of necessary #endif directives changes according to whether the elseif or #else directive is used.

C Syntax

(#ifdef identifier newline );

Sample - C Code

#include <stdio.h>
#define wikitechy 16
void main()
 {
    #ifdef  wikitechy
    printf("Hello! welcome to wikitechy\n");
    #else
    printf("www.wikitechy.com\n");
    #endif
}

C Code - Explanation

code-explanation-preprocessors-ifdef
  1. In C programming #include<stdio.h> specifies a statement which tells the compiler to insert the contents of stdio at that particular place. A header file is a C file, that typically ends in ".h".
  2. In this example, #define WIKITECHY 16 defines the constant name (WIKITECHY) with its value (16).
  3. In this example, #ifdef WIKITECHY specifies this directive checks whether the identifier(WIKITECHY) is currently defined, there by executing the statement “Hello! welcome to wikitechy”.
  4. The command #elseif simply truncates the if statement and prints the else statement www.wikitechy.com.
  5. In this example, #endif specifies the end of the program.

Sample Output - Programming Examples

code-explanation-preprocessors-ifdef-output
  1. Here in this output the “Hello! welcome to wikitechy” is printed in the console window since the ifdef directive defines that the identifier(WIKITECHY) is currently defined.
code-explanation-preprocessors-ifdef-output1
  1. Here in this output , the ifdef directive doesn’t define the identifier(WIKITECHY) so the else statement prints the statement “www.wikitechy.com”.

View More Quick Examples


Related Searches to c preprocessors ifdef