What else does the condition operator in C++ do for me?
I have got a strange compile error while using condition operator.
a,b
are int
value, and the following expression get compile error.
(a>b)?( std::cout << a ) : ( b=MAX );
16 (b <unknown operator> 5)'
(a>b)?( a=MAX ) : ( std::cout<<b );
16 (&std::cout)->std::basic_ostream<_CharT, _Traits>::operator<< [with _CharT = char, _Traits = std::char_traits<char>](b)'
But this expression works well, which is odd..
(a>b)?( std::cout << a ) : ( std::cout<<b );
I have no idea what makes such a difference, and don't know why the compile error stand for. Here is my gcc info:
Reading specs from ./../lib/gcc/mingw32/3.4.2/specs
Configured with: ../gcc/configure --with-gcc --with-gnu-ld --with-gnu-as --host=
mingw32 --target=mingw32 --prefix=/mingw --enable-threads --disable-nls --enable
-languages=c,c++,f77,ada,objc,java --disable-win32-registry --disable-shared --e
nable-sjlj-exceptions --enabl开发者_StackOverflow中文版e-libgcj --disable-java-awt --without-x --enable-ja
va-gc=boehm --disable-libgcj-debug --enable-interpreter --enable-hash-synchroniz
ation --enable-libstdcxx-debug
Thread model: win32
gcc version 3.4.2 (mingw-special)`
The conditional operator must always return the same type. In your first example,
(a > b) ? (std::cout << a) : (b = MAX);
the first branch yields the type std::ostream
and the second branch yields the type of b
(which is likely an integer, given its context). Your second example,
(a > b) ? (std::cout << a) : (std::cout << b);
has no such problem because both branches return the same type, std::ostream
. In either case, it would likely be cleaner to handle these conditions with a simple if
-else
statement. The conditional operator tends to hurt readability and is typically only useful when conditionally assigning to a variable:
int a = (a > b) ? a : b;
std::cout << a;
The ?:
is an operator in an expression (or sub-expression). An expression has a type. What should the type of (a > b) ? (std::cout << a) : (b = MAX)
be. Types in C++ are evaluated statically, and there's no way the compiler can determine a common type for std::cout << a
(type std::ostream&
) and b = MAX
(type int
).
What else does the condition operator in C++ do for me ?
Well, it does type matching of the second and third arguments, and that can be quite useful as a way of extracting types from expressions. For a mind blowing article on how to use that feature of the conditional operator, read here
精彩评论