What else does the condition statement in C ++ do for me?

I got a weird compilation error when using the condition statement.

a,b are int values, and the following expression gets a compilation 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 I don't know why a compilation error occurs. 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)` 
+6
source share
3 answers

A conditional statement must always return the same type. In the first example

 (a > b) ? (std::cout << a) : (b = MAX); 

the first branch gives the type std::ostream , and the second branch gives the type b (which is probably an integer, given its context). Your second example

 (a > b) ? (std::cout << a) : (std::cout << b); 

doesn't have such a problem, because both branches return the same type, std::ostream . In any case, it would probably be cleaner to handle these conditions with a simple if - else . A conditional statement tends to degrade readability and is usually only useful when conditionally assigning a variable:

 int a = (a > b) ? a : b; std::cout << a; 
+14
source

?: - operator in the expression (or subexpression). The expression is of type. What should be the type (a > b) ? (std::cout << a) : (b = MAX) (a > b) ? (std::cout << a) : (b = MAX) . Types in C ++ are evaluated statically, and the compiler cannot determine the generic type for std::cout << a (type std::ostream& ) and b = MAX (type int ).

+4
source

What else does a condition statement in C ++ do for me?

Well, this is the type of correspondence of the second and third arguments, and it can be quite useful as a way of extracting types from expressions. For a bloated article on how to use this function of a conditional statement, read here

+2
source

Source: https://habr.com/ru/post/892211/


All Articles