C言語菜鳥基礎教程の判断
(一)
まずプログラムを作成します。
if(0)に変更すると、運転結果がなく、printf()文が実行されていないことが分かります。
C言語は判断文のいずれかの非0または非空の値を真と見なす。だからif(1)、if(2)、if(5)、if(100)、if(-10)の効果は同じです。
(二)
もう一つのプログラムを作成します。
a=100,a>0は成立するので、if(a>0)はif(1)に等しい。
C言語では、判定文に値があるか、1か、それとも0かを指定します。例えば、本プログラムのa>0の値は1です。
(三)
最後にプログラムを作成します。
まずプログラムを作成します。
#include <stdio.h>
int main()
{
if(1)
{
printf("The condition is true!
");
}
return 0;
}
実行結果:The condition is true!
もう1を順に、2、5、100、-10に変えたら、運行結果は全く同じです。if(0)に変更すると、運転結果がなく、printf()文が実行されていないことが分かります。
C言語は判断文のいずれかの非0または非空の値を真と見なす。だからif(1)、if(2)、if(5)、if(100)、if(-10)の効果は同じです。
(二)
もう一つのプログラムを作成します。
#include <stdio.h>
int main()
{
int a = 100;
if(a > 0)
{
printf("The condition value is %d
", (a > 0));
}
return 0;
}
実行結果:The condition value is 1
分析:a=100,a>0は成立するので、if(a>0)はif(1)に等しい。
C言語では、判定文に値があるか、1か、それとも0かを指定します。例えば、本プログラムのa>0の値は1です。
(三)
最後にプログラムを作成します。
#include <stdio.h>
int main()
{
char c1 = '\0';
if(c1)
{
printf("The condition is true!
");
}
else
{
printf("The condition is false!
");
}
char c2 = ' ';
if(c2)
{
printf("The condition is true!
");
}
else
{
printf("The condition is false!
");
}
char c3 = 'A';
if(c3)
{
printf("The condition is true!
");
}
else
{
printf("The condition is false!
");
}
return 0;
}
実行結果:
The condition is false!
The condition is true!
The condition is true!
説明:C言語では'\0'で空の文字を表します。スペース''も1文字です。これはif(c 2)の条件から本当に分かります。