short if code example

Example 1: java shortest if else statement

(myNumber == 12) ? "true" : "false"

Example 2: c# ternary

// ---------------- Syntax of Ternary Operators ----------------- //

string stateOfMatter;
int temperature = 23;


// ---- For just one condition ---- //
stateOfMatter = temperature < 0 ? "Solid": "Liquid";
  
// If temperature is below zero, then stateOfMatter is solid, otherwise
// it will be liquid
  
  
// ---- For more conditions ---- //
stateOfMatter = temperature < 0 ? "Solid" : (temperature > 100 ? "Gas" : "Liquid");

Example 3: conditional operator

var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"

Example 4: c# ternary condition

condition ? consequent : alternative

Example 5: shorten if condition c++

(condition) ? (if_true) : (if_false)

Example 6: short for if

#include <iostream>

//Another variation:
    a == 1 ? std::cout << "1" : (a == 2 ? std::cout << "2"  : a = 3);

//This is the same as:
if(a == 1)
{
    std::cout << "1";    
}
else if (a == 2)
{
    std::cout << "2";
}
else
{
    a = 3;
}

Tags:

C Example