C语言中在用到循环语句时,我们都会涉及到表达式真假判断,‘真值’有哪些?'假值'有哪些?
我们用代码来实现看看
tf.c
1 /*********************************************************************************
2 * Copyright: (C) 2018 lingyun
3 * All rights reserved.
4 *
5 * Filename: tf.c
6 * Description: This file
7 *
8 * Version: 1.0.0(07/14/2018)
10 * ChangeLog: 1, Release initial version on "07/14/2018 02:49:55 PM"
11 *
12 ********************************************************************************/
13 #include <stdio.h>
14
15 int main(void)
16 {
17 int true_value,false_value;
18
19 true_value = (2>1);
20 false_value = (2<1);
21
22 printf("tru = %d, false = %d;\n",true_value,false_value);
23
24 return 0 ;
25 }
运行结果:
[a4729821@JYstd c_test]$ gcc tf.c
[a4729821@JYstd c_test]$ ./a.out
tru = 1, false = 0;
trust.c
2 * Copyright: (C) 2018 lingyun
3 * All rights reserved.
4 *
5 * Filename: trust.c
6 * Description: This file
7 *
8 * Version: 1.0.0(07/14/2018)
10 * ChangeLog: 1, Release initial version on "07/14/2018 02:34:29 PM"
11 *
12 ********************************************************************************/
13 #include <stdio.h>
14
15 int main(void)
16 {
17 int n = 4;
18
19 while(n)
20 printf("%2d is trust;\n",n--);
21 printf("%2d is false;\n",n);
22
23 n = -4;
24 while(n)
25 printf("%2d is trust;\n",n++);
26 printf("%2d is false;\n",n);
27
28 return 0;
29 }
30
运行结果:
[a4729821@JYstd c_test]$ gcc trust.c
[a4729821@JYstd c_test]$ ./a.out
4 is trust;
3 is trust;
2 is trust;
1 is trust;
0 is false;
-4 is trust;
-3 is trust;
-2 is trust;
-1 is trust;
0 is false;
总结:表达式为真的值为1,表达式假的值为0;
while条件判断语句为真就会循环,所以可以知道,一般来说,所有非零值都视为真,只有假被视为假;while(n)“n只要是非零值”都会无限循环;