DEV Community

islomAli99
islomAli99

Posted on

5 1

C++ Ternary Operator

Assalamu aleykum bugun sizlar bilan C++ dasturlash tilida ishlatiladigon Ternary Operator buni tarjimasi - uchlik operatori xaqida gaplashib o'tamiz.

Uchlik operator sinov shartini baholaydi va shart natijasi asosida kod blokini bajaradi.

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

Natija:

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

Uchlik operatoridan qachon foydalanish kerak?

C++ da uchlik operatori if...else ifodalarining ayrim turlarini almashtirish uchun ishlatilishi mumkin.

Masalan, biz ushbu kodni almashtirishimiz mumkin

#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

Misol uchun shuni ternaryda qilingan variant:

#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

Bu erda ikkala dastur ham bir xil natijani beradi. Biroq, uchlik operatoridan foydalanish bizning kodimizni yanada o'qilishi va toza qiladi.

Eslatma: Agar natija qisqa bo'lsa, biz uchlik operatoridan foydalanishimiz kerak.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay