C语言进阶剖析 18 三目运算符和逗号表达式

三目运算符

  • 三目运算符(a ? b : c)可以作为逻辑运算的载体
  • 规则 : 当 a 为真时,返回 b 的值; 否则返回 C 的值

下面的程序运行结束后,a,b,c的值分别会是多少呢?

int a = 1;
int b = 2;
int c = 0;
c = a < b ? a : b;
(a < b ? a : b) = 3;  // error: lvalue required as left operand of assignment

实例分析: 三目运算符初探

#include <stdio.h>

int main()
{
    int a = 1;
    int b = 2;
    int c = 0;
    
    c = a < b ? a : b;
    
    // (a < b ? a : b) = 3;
    
    printf("%d\n", a);
    printf("%d\n", b);
    printf("%d\n", c);
}
输出:
1
2
1

分析:【三目运算符返回 a 或 b 的数值】
(a < b ? a : b) = 3; ==> error: lvalue required as left operand of assignment

对变量进行操作:

  • *(a < b ? &a : &b) = 3
  • 三目运算符的返回类型
        ○ 通过隐式类型转换规则返回 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));
    printf("%d\n", sizeof(i ? i : d));
    // printf("%d\n", sizeof(d ? d : p));

    return 0;
}
输出:
4
8
分析:
d ? d : p ==> error: type mismatch in conditional expression

逗号表达式

  • 逗号表达式是 C 语言的 "粘贴剂"
  • 逗号表达式用于将多个子表达式连接为一个表达式
  • 逗号表达式的值为最后一个子表达式的值
  • 逗号表达式中的前 N-1 个子表达式可以没有返回值
  • 逗号表达式按照从左向右的顺序计算每个子表达式的值
        ○ exp1, exp2, exp3, …, expN;

实例分析:逗号表达式的示例

#include <stdio.h>

void hello(void)
{
    printf("Hello\n");
}

int main()
{
    int a[3][3] = {
        (0, 1, 2),
        (3, 4, 5),
        (7, 8, 9)
    };
    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
a[0][0] = 2
a[0][1] = 5
a[0][2] = 9
a[1][0] = 0
a[1][1] = 0
a[1][2] = 0
a[2][0] = 0
a[2][1] = 0
a[2][2] = 0

分析:
while( i < 5 )
    printf("i = %d\n", i),

hello(),

i ++;
==> while( i < 5 ) printf("i = %d\n", i), hello(), i ++;
----------------------------------------------------------
    int a[3][3] = {
    (0, 1, 2),
    (3, 4, 5),
    (7, 8, 9)
};
==>
int a[3][3] = {
    (2),
    (5),
    (9)
};

编程实验: 一行代码实现 strlen

#include <stdio.h>
#include <assert.h>

int strlen_g(const char* s)
{
    return (assert(s), *s ? strlen_g(s + 1) + 1 : 0);
}

int main()
{
    printf("%d\n", strlen_g("D.T.Software"));
    printf("%d\n", strlen_g(NULL));

    return 0;
}
输出:
12
a.out: test.c:6: strlen: Assertion `s' failed.
Aborted


小结

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

内容参考狄泰软件学院系列课程,如有侵权,请联系作者删除!感谢~

发布了334 篇原创文章 · 获赞 661 · 访问量 130万+

猜你喜欢

转载自blog.csdn.net/czg13548930186/article/details/86604604