Home > Article > Backend Development > Some interesting observations about the C/C++ ternary operator
We know that the ternary operator is implemented instead of if..else clause. It is represented by ?:. '? The ' symbol is equivalent to the if part, and ':' is equivalent to the else part. The following 3 programs explain some interesting observations in the case of the ternary operator.
The following program compiles without any errors. The return type of a ternary expression is expected to be float (like exp2), and exp3 (that is, a literal zero - int type) is implicitly convertible to float.
#include <iostream> using namespace std; int main(){ int test1 = 0; float fvalue = 3.111f; cout<< (test1 ? fvalue : 0) << endl; return 0; }
The following program will not compile because the compiler cannot locate or find the return type of the ternary expression, or there is no implicit conversion between exp2 (char array) and exp3 (int).
#include <iostream> using namespace std; int main(){ int test1 = 0; cout<< test1 ? "A String" : 0 << endl; return 0; }
The following program may be able to compile, but fail when run. The return type of a ternary expression is restricted to type (char *), but the expression returns an int, so the program fails. Literally, the program attempts to print the string at address 0 at execution time or runtime.
#include <iostream> using namespace std; int main(){ int test1 = 0; cout << (test1 ? "A String" : 0) << endl; return 0; }We can observe that exp2 is treated as output type and exp3 will be able to be converted to exp2 at execution time or runtime. If the conversion is considered implicit, the compiler will Insert converted stub. The compiler will throw an error if the conversion is treated as an explicit operation. If any compiler is able to ignore such errors, the program may fail at execution time or runtime.
The above is the detailed content of Some interesting observations about the C/C++ ternary operator. For more information, please follow other related articles on the PHP Chinese website!