DEV Community

Cover image for C++ Ternary Operator
Islamali Akhmadjanov
Islamali Akhmadjanov

Posted on

1

C++ Ternary Operator

Ассаламу алейкум, сегодня мы поговорим с вами о переводе Тернарного оператора, используемого в языке программирования C++ — тернарный оператор.

Тернарный оператор оценивает тестовое условие и выполняет блок кода на основе результата условия.

Image description

#include <iostream>

using namespace std;

int main() 
{
  double marks;

  // take input from users
  cout << "Enter your marks: ";
  cin >> marks;

  // ternary operator checks if
  // marks is greater than 40
  string result = (marks >= 40) ? "passed" : "failed";

  cout << "You " << result << " the exam.";

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Результат:

Enter your marks: 80
You passed the exam.
Enter fullscreen mode Exit fullscreen mode

Когда использовать тернарный оператор?

В C++ тернарный оператор можно использовать для замены некоторых типов операторов if...else.

Например, мы можем заменить этот код

#include <iostream>

using namespace std;

int main() 
{
  // Create a variable
  int number = -4;

  if (number > 0)
  {
    cout << "Positive Number"; 
  }
  else
  {
    cout << "Negative Number!";
  }

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Например, этот вариант выполнен в тернарном виде:

#include <iostream>
#include <string>

using namespace std;

int main() 
{
  int number = -4;
  string result;

  // Using ternary operator
  result = (number > 0) ? "Positive Number!" : "Negative Number!";

  cout << result << endl;

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

`Здесь обе программы дают одинаковый результат. Однако использование тернарного оператора делает наш код более читабельным и чистым.

Примечание. Если результат короткий, нам нужно использовать тернарный оператор`

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay