Condicionais
Instruções condicionais permitem que seu programa tome decisões. Veja como if/else e switch funcionam em diferentes linguagens.
Instruções If/Else
- JavaScript
- PHP
- Rust
- Go
- Python
- Zig
- C#
- C++
- C
- Java
- Ruby
- Swift
// Basic if/else
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Ternary operator
const status = age >= 18 ? "Adult" : "Minor";
// Nested ternary
const result = x > 0 ? (y > 0 ? "Both positive" : "X positive") : "X not positive";
// Chained ternary
const grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
// Else if
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}
<?php
// Basic if/else
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
// Ternary operator
$status = $age >= 18 ? "Adult" : "Minor";
// Nested ternary
$result = $x > 0 ? ($y > 0 ? "Both positive" : "X positive") : "X not positive";
// Chained ternary (PHP 7.4+ null coalescing)
$grade = $score >= 90 ? "A" : ($score >= 80 ? "B" : "C");
// Else if
if ($score >= 90) {
$grade = "A";
} elseif ($score >= 80) {
$grade = "B";
} else {
$grade = "C";
}
// Basic if/else
if age >= 18 {
println!("Adult");
} else {
println!("Minor");
}
// Ternary operator (if as expression)
let status = if age >= 18 { "Adult" } else { "Minor" };
// Nested ternary
let result = if x > 0 {
if y > 0 { "Both positive" } else { "X positive" }
} else {
"X not positive"
};
// Else if
let grade = if score >= 90 {
"A"
} else if score >= 80 {
"B"
} else {
"C"
};
// Basic if/else
if age >= 18 {
fmt.Println("Adult")
} else {
fmt.Println("Minor")
}
// Ternary operator - Go doesn't have traditional ternary
// Use if/else expression pattern instead
var status string
if age >= 18 {
status = "Adult"
} else {
status = "Minor"
}
// If with initialization
if status := "Adult"; age >= 18 {
fmt.Println(status)
}
// Else if
if score >= 90 {
grade = "A"
} else if score >= 80 {
grade = "B"
} else {
grade = "C"
}
# Basic if/else
if age >= 18:
print("Adult")
else:
print("Minor")
# Ternary operator (Python 2.5+)
status = "Adult" if age >= 18 else "Minor"
# Nested ternary
result = "Both positive" if x > 0 and y > 0 else ("X positive" if x > 0 else "X not positive")
# Chained ternary
grade = "A" if score >= 90 else ("B" if score >= 80 else "C")
# Elif
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
// Basic if/else
if (age >= 18) {
std.debug.print("Adult\n", .{});
} else {
std.debug.print("Minor\n", .{});
}
// Ternary operator (if as expression)
const status = if (age >= 18) "Adult" else "Minor";
// Nested ternary
const result = if (x > 0)
(if (y > 0) "Both positive" else "X positive")
else
"X not positive";
// Else if
const grade = if (score >= 90) "A"
else if (score >= 80) "B"
else "C";
// Basic if/else
if (age >= 18)
{
Console.WriteLine("Adult");
}
else
{
Console.WriteLine("Minor");
}
// Ternary operator
string status = age >= 18 ? "Adult" : "Minor";
// Nested ternary
string result = x > 0 ? (y > 0 ? "Both positive" : "X positive") : "X not positive";
// Chained ternary
string grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
// Else if
if (score >= 90)
{
grade = "A";
}
else if (score >= 80)
{
grade = "B";
}
else
{
grade = "C";
}
// Basic if/else
if (age >= 18) {
std::cout << "Adult" << std::endl;
} else {
std::cout << "Minor" << std::endl;
}
// Ternary operator
std::string status = age >= 18 ? "Adult" : "Minor";
// Nested ternary
std::string result = x > 0 ? (y > 0 ? "Both positive" : "X positive") : "X not positive";
// Chained ternary
std::string grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
// Else if
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}
// Basic if/else
if (age >= 18) {
printf("Adult\n");
} else {
printf("Minor\n");
}
// Ternary operator
const char* status = age >= 18 ? "Adult" : "Minor";
// Nested ternary
const char* result = x > 0 ? (y > 0 ? "Both positive" : "X positive") : "X not positive";
// Chained ternary
char grade = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C';
// Else if
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else {
grade = 'C';
}
// Basic if/else
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
// Ternary operator
String status = age >= 18 ? "Adult" : "Minor";
// Nested ternary
String result = x > 0 ? (y > 0 ? "Both positive" : "X positive") : "X not positive";
// Chained ternary
String grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
// Else if
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}
# Basic if/else
if age >= 18
puts "Adult"
else
puts "Minor"
end
# Ternary operator
status = age >= 18 ? "Adult" : "Minor"
# Nested ternary
result = x > 0 ? (y > 0 ? "Both positive" : "X positive") : "X not positive"
# Chained ternary
grade = score >= 90 ? "A" : score >= 80 ? "B" : "C"
# Elsif
if score >= 90
grade = "A"
elsif score >= 80
grade = "B"
else
grade = "C"
end
// Basic if/else
if age >= 18 {
print("Adult")
} else {
print("Minor")
}
// Ternary operator
let status = age >= 18 ? "Adult" : "Minor"
// Nested ternary
let result = x > 0 ? (y > 0 ? "Both positive" : "X positive") : "X not positive"
// Chained ternary
let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C"
// Else if
if score >= 90 {
grade = "A"
} else if score >= 80 {
grade = "B"
} else {
grade = "C"
}
Instruções Switch/Case
- JavaScript
- PHP
- Rust
- Go
- Python
- Zig
- C#
- C++
- C
- Java
- Ruby
- Swift
// Switch statement
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Other day");
}
// Switch expression (no break needed)
switch (day) {
case 1: return "Monday";
case 2: return "Tuesday";
default: return "Other";
}
<?php
// Switch statement
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
default:
echo "Other day";
}
// Match expression (Rust's switch)
match day {
1 => println!("Monday"),
2 => println!("Tuesday"),
_ => println!("Other day"),
}
// Match as expression
let day_name = match day {
1 => "Monday",
2 => "Tuesday",
_ => "Other day",
};
// Switch statement
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
default:
fmt.Println("Other day")
}
// Switch without condition
switch {
case day == 1:
fmt.Println("Monday")
case day == 2:
fmt.Println("Tuesday")
}
# Python 3.10+ match/case
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case _:
print("Other day")
# Traditional approach (dict)
days = {
1: "Monday",
2: "Tuesday"
}
print(days.get(day, "Other day"))
// Switch expression
const day_name = switch (day) {
1 => "Monday",
2 => "Tuesday",
else => "Other day",
};
// Switch statement
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
default:
Console.WriteLine("Other day");
break;
}
// Switch expression (C# 8+)
string dayName = day switch
{
1 => "Monday",
2 => "Tuesday",
_ => "Other day"
};
// Switch statement
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
default:
std::cout << "Other day" << std::endl;
}
// Switch statement
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
default:
printf("Other day\n");
}
// Switch statement
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
}
// Switch expression (Java 14+)
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Other day";
};
# Case statement
case day
when 1
puts "Monday"
when 2
puts "Tuesday"
else
puts "Other day"
end
# Case as expression
day_name = case day
when 1 then "Monday"
when 2 then "Tuesday"
else "Other day"
end
// Switch statement
switch day {
case 1:
print("Monday")
case 2:
print("Tuesday")
default:
print("Other day")
}
// Switch with ranges
switch score {
case 90...100:
grade = "A"
case 80..<90:
grade = "B"
default:
grade = "C"
}
Principais Conclusões
-
Sintaxe if/else -- Linguagens da família C (C, C++, Java, JavaScript, C#) usam chaves e
else if; Python usaelifcom dois-pontos e indentação; Ruby usaelsifeend; PHP usaelseif(uma palavra). O estilo Pythonif cond:sem chaves reduz ruído visual, mas exige indentação consistente. Se você prefere delimitadores de bloco explícitos e vem de C/Java, escolha uma linguagem baseada em chaves; se valoriza concisão e legibilidade, Python ou Ruby podem parecer mais limpos. -
Switch vs match -- O
switchestilo C (C, C++, Java, JavaScript, PHP) exigebreakpara evitar fallthrough; esquecê-lo é um bug comum. Omatchde Rust é baseado em expressões — retorna um valor e não tem fallthrough, entãolet x = match n { 1 => "one", _ => "other" };é idiomático. Python 3.10+ e C# 8+ adicionam expressõesmatch/switchcom pattern matching. Para lógica com múltiplas ramificações, prefiramatchde Rust ou Swift quando a exaustividade importa; useswitchestilo C quando precisar de fallthrough explícito ou trabalhar em bases de código legado. -
Operadores ternários -- A maioria das linguagens usa
cond ? a : b(C, C++, Java, JavaScript, C#, Swift, PHP). Go deliberadamente omite?:e usaif cond { a } else { b }para atribuição, favorecendo clareza sobre brevidade. Python usaa if cond else b(condição no meio). Rust e Zig usamifcomo expressões:let x = if cond { a } else { b };. Se você quer condicionais inline compactas, use ternário; se prefere a explicitude do estilo Go, evite ternários aninhados e favoreça blocos if/else simples. -
Expressão vs instrução -- Em Rust, Zig e Ruby,
ifpode ser uma expressão que produz um valor; C, Java e Go tratamifapenas como instrução. JavaScript usa ternário para expressões. Isso afeta como você atribui condicionalmente: Rust permitelet grade = if score >= 90 { "A" } else { "B" };sem uma variável separada e múltiplas atribuições. Escolha linguagens baseadas em expressões quando quiser evitar estado mutável e escrever código mais declarativo. -
Quando escolher qual -- Para programação de sistemas ou máxima explicitude, o if/else de Go e a ausência de ternário reduzem surpresas. Para código funcional e orientado a expressões, Rust e Zig se destacam. Para prototipagem rápida e legibilidade, o
elifea if cond else bde Python são acessíveis. Para backends empresariais ou web, C#, Java e PHP oferecem condicionais familiares no estilo C com boas ferramentas.