Some interesting observations about the C/C++ ternary operator

PHPz
Release: 2023-09-15 19:29:02
forward
1116 people have browsed it

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  using namespace std; int main(){ int test1 = 0; float fvalue = 3.111f; cout<< (test1 ? fvalue : 0) << endl; return 0; }
Copy after login

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  using namespace std; int main(){ int test1 = 0; cout<< test1 ? "A String" : 0 << endl; return 0; }
Copy after login

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  using namespace std; int main(){ int test1 = 0; cout << (test1 ? "A String" : 0) << endl; return 0; }
Copy after login
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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!