Jump to: navigation, search

Description

Conditionally execute a statement or one of two statements.

Details

if (expression)
  statement;

Will evaluate the scalar expression in parentheses and if it compares not equal to zero will execute the statement.

if (expression)
   statement1;
else
   statement2;

Will execute statement1 if expression compares not equal to zero. Will instead execute statement2 if expression compares equal to zero.

Either or both statements can be a compound statement.

Examples

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
   if (argc < 1) {
      puts("I don't even know my own name!");
      return EXIT_FAILURE;
   }

   if (strcmp(argv[0],"what_am_i_called") != 0)
      puts("If renamed, this program will print its name");
   else
      printf("My name is %s",argv[0]);
   return EXIT_SUCCESS;
}

Grammar

<c_grammar>selection-statement:

 if ( expression ) statement
 if ( expression ) statement else statement
 switch ( expression ) statement

</c_grammar>

References

  • ISO C99 Standard, 3.8.4.1
Personal tools