Ask coding questions

← Back to all posts
which if better switch, or if?
mootian (0)

if you use C you probably know what I mean, I don't know about other languages, but, which is better switch-default or if-else?

Answered by SixBeeps (5335) [earned 5 cycles]
View Answer
Comments
hotnewtop
SixBeeps (5335)

Switch blocks and if statements are both used as conditionals, but it really depends on what you plan on doing with them. It's kinda like the difference between a while loop and a for loop. Both are used for looping, but their structures and uses are different.

Because of that, one is not necessarily "better" than the other. You'll have to use your judgement to determine when to use each one.

Coder100 (18904)

They are NOT even the same thing, please no.
switch uses labels and can only support only expressions that return to integers and chars (technically chars is an expression that returns to int).

if does not use labels, and can support any expression that returns to bool.

They don't do the same thing, but switch is generally better for said things (matching).

Have you tried the language rust? They have a much better switch that can support many things :drool:

let x: String = String::from("match me");

match x {
  String::from("match me") => println!(":drool:"),
  _ => println!("wow")
}