DEV Community

Islamali Akhmadjanov
Islamali Akhmadjanov

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.

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Sentry image

Make it make sense

Make sense of fixing your code with straight-forward application monitoring.

Start debugging →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay