DEV Community

Cover image for C++ Ternary Operator
islomAli99
islomAli99

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

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

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay