法大奥山研究室

 previous  contents

14.3. if文


 選択文(Selection Statement)には if文と switch文があり,いずれも条件分岐します。ここでは if文を見ます。

■if文(if Statement)

if (式) 文
if (式) 文 else 文

条件式 が真であるとき,続く 文 を実行します。else がある場合には条件式 が偽のときに else の後の 文 を実行します。文 とは,複合文,式文,if文などの「文」のことです。

 関係演算子や論理演算子より,条件式 が真であるとは式 が 0 以外のときとなります。

/* Example 14.2 */

#include <stdio.h>

int main(void)
{
       int x = 0;
       printf("Input an integer: ");
       scanf("%d", &x);
       if(x)
              printf("Ok, x = %d.\n", x);
       else
       {
              printf("Input a nonzero integer: ");
              scanf("%d", &x);
              printf("Well, x = %d.\n", x);
       }
       return 0;
}

この例では式 x が真(0 以外)であれば,続く式文を実行し,偽の場合には else の後の複合文を実行します。次は実行例です。(太字部分が入力箇所です。)

% ./a.out
Input an integer: 0
Input a nonzero integer: 7
Well, x = 7.
% ./a.out
Input an integer: 9
Ok, x = 9.

 previous  contents