# 第18课 三目运算符与逗号表达式

·三目运算符（a?b:c）可以作为逻辑运算的载体
·规则：当a为真时，返回b的值；否则返回c的值

# include"stdio.h"

int main()
{

``````int a = 1;
int b = 2;
int c = 0;
c =a<b? a:b;
printf("%d\n",a);
printf("%d\n",b);
printf("%d\n",c);
return 0;``````

}

1
2
1
·三目运算符（a?b:c）的返回类型
-通过隐式类型转换规则返回b和c中的较高类型
-当b和c不能隐式转换到同一类型时将编译出错

# include "stdio.h"

int main()
{

``````char c = 0;
short s = 0;
int i = 0;
double d = 0;
char *p ="str";
printf("%d\n",sizeof(c? c : s)); //4
printf("%d\n",sizeof(i? i : d)); //8
//printf("%d\n",sizeof(d? d : p)); //error``````

}

4
8
//printf("%dn",sizeof(d? d : p)); //error

·逗号表达式是C语言中的“粘贴剂”
·逗号表达式用于将多个子表达式连接为一个表达式
·逗号表达式的值为最后一个子表达式的值
·逗号表达式中的前N-1个子表达式可以没有返回值
·逗号表达式按照从左向右的顺序计算每个子表达式的值

# include "stdio.h"

void hello()
{

``printf("Hello!\n");``

}
int main()
{

``````int a[3][3] = {
(0,1,2),
(3,4,5),
(6,7,8)
};
int i = 0;
int j = 0;
while(i<5)
printf("i = %d\n",i),
hello(),
i ++;
for(i = 0; i <3; i++)
{
for(j = 0;j < 3;j ++)
{
printf("a[%d][%d] = %d\n",i,j,a[i][j]);
}
}
return 0;``````

}

i = 0
Hello!
i = 1
Hello!
i = 2
Hello!
i = 3
Hello!
i = 4
Hello!
a0 = 2
a0 = 5
a0 = 8
a1 = 0
a1 = 0
a1 = 0
a2 = 0
a2 = 0
a2 = 0

# include "assert.h"

int strlen(const char*s)
{

``return assert(s),(*s ? strlen(s + 1) + 1 : 0);``

}
int main()
{

``````printf("len = %d\n",strlen("zhangyingli"));
printf("len = %d\n",strlen(NULL));
return 0;``````

}

len = 11
Assertion failed: s, file 18-4.c, line 6

·三目运算符返回变量的值，而不是变量本身
·三目运算符通过隐式类型转换规则确认返回值类型
·逗号表达式按照从左向右的顺序计算每个子表达式的值
·逗号表达式的值为最后一个子表达式的值