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 --enable-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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With