Home > Backend Development > C++ > What does ? mean in c++?

What does ? mean in c++?

下次还敢
Release: 2024-04-26 19:21:15
Original
965 people have browsed it

The ? in C is used as a conditional operator to return different values ​​based on conditions. Syntax: condition ? true value : false value. Can be used to quickly change variable values ​​or select operations. Conditional operators can be nested, and different conditions return different truth values.

What does ? mean in c++?

#What does ? in C mean?

In C, the ? symbol is used for conditional operators (also called ternary operators). A conditional operator is a shorthand form for evaluating a condition and returning a different value depending on whether the condition is true or false.

Syntax:

<code>条件 ? 真值 : 假值</code>
Copy after login

Where:

  • Condition: The Boolean expression to be evaluated.
  • True value: The value returned if the condition is true.
  • False value: The value returned if the condition is false.

Usage:

Conditional operators are often used to quickly change the value of a variable or select a different action based on a condition. For example:

<code class="c++">int age = 25;
std::string message = (age >= 18) ? "成年人" : "未成年人";</code>
Copy after login

In this example, message is assigned different values ​​based on the value of age. If age is greater than or equal to 18, message is "adult", otherwise "minor".

Nested conditional operators:

Conditional operators can be nested, which means that the true or false value of one conditional operator can be the true or false value of another conditional operator. symbol. For example:

<code class="c++">int score = 90;
char grade = (score >= 90) ? 'A' : (score >= 80) ? 'B' : 'C';</code>
Copy after login

In this example, grade is assigned a different value based on the value of score:

  • If If score is greater than or equal to 90, then grade is 'A'.
  • If score is greater than or equal to 80, but less than 90, then grade is 'B'.
  • Otherwise, grade is 'C'.

The above is the detailed content of What does ? mean in c++?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c++
source:php.cn
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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template