c++ 和 c 三目运算符区别
三目运算符
三目运算表达式:<表达式1>?<表达式2>:<表达式3>
例如:
(a>b) ? a:b
C和C++中三目运算符区别
- 在c语言中,三目运算符返回变量的值,即不能当左值。
编译报错,提示 (a<b ? a:b) 不能当左值:#include<stdio.h> int main() { int a = 10 ; int b = 20 ; (a<b ? a:b) = 30; printf("a=%d",a); return 0; }
[root@8a7aa77a8ba4 ~]# gcc test.c test.c: 在函数‘main’中: test.c17: 错误:赋值运算的左操作数必须是左值 (a<b ? a:b) = 30; ^
- 在c++中,三目运算符返回变量本身,即可以当左值。
输出结果:#include<iostream> using namespace std; int main() { int a = 10 ; int b = 20 ; (a<b ? a:b) = 30; cout<<"a="<<a<<endl; return 0; }
a=30
如何让c语言的三目运算符当左值?
要让c语言三目运算符当左值,只需要三目运算符返回变量本身,即可以如下操作:*(a<b ? &a:&b) = 30
输出结果:#include<stdio.h> int main() { int a = 10 ; int b = 20 ; *(a<b ? &a:&b) = 30; printf("a=%d\n",a); return 0; }
a=30
本作品采用《CC 协议》,转载必须注明作者和本文链接