Ternary Operator क्या है
Ternary operator एक छोटी एक-line choice है: 'क्या बारिश हो रही है? umbrella लो, नहीं तो sunglasses लो'। यह बिना पूरे if-else के दो values में से चुनता है।
In this page:
Syntax
type result = condition ? valueIfTrue : valueIfFalse;
The Ternary Operator
Ternary operator condition ? valueIfTrue : valueIfFalse एक साधारण if/else का एक compact one-line विकल्प है। यह हमेशा अपने दो branches में से बिल्कुल एक evaluate होता है। Ternary expressions को nest किया जा सकता है लेकिन ऐसा करना जल्दी readability को नुकसान पहुंचाता है।
Note:
छोटे, simple value selection के लिए ternary का उपयोग करें — logic जटिल होने पर
if/else पर वापस जाएं।उदाहरण: The Ternary Operator
using System;
class Program
{
static void Main(string[] args)
{
int age = 16;
string status = age >= 18 ? "adult" : "minor";
Console.WriteLine(status);
Console.WriteLine(age % 2 == 0 ? "even" : "odd");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- कई
?:operators को nest करना जिससे code पढ़ना मुश्किल हो जाता है। - अलग types की branches का उपयोग करना जिनमें कोई common type न हो, जो एक compile error है।
- Ternary operator को किसी expression के बजाय एक statement की तरह उपयोग करना, जैसे
x > 0 ? Print() : Skip();।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: