Skip to content

What is the difference between a switch statement and an if-else statement (C++ programming)

Xeronator··1 votes·767 views

Does anyone know?

If i used an if-else statement or a switch statement for the same problem, will it still give me the same output?

(sorry im still a newbie in C++ lol)

4 Comments

Baval2 votes

switch is more commonly used for multiple possible outputs. if you want 6 responses depending on input a switch is better than if x then y else if c then z else if etc etc

but if theyre both programmed correctly they can function identically, just one will be more optimized

Hethalean3 votes

{quoted}

switch is more commonly used for multiple possible outputs. if you want 6 responses depending on input a switch is better than if x then y else if c then z else if etc etc

but if theyre both programmed correctly they can function identically, just one will be more optimized

Another difference is that switch statements can only work with static preknown at compile time values.

Baval1 votes

{quoted}

Another difference is that switch statements can only work with static preknown at compile time values.

unless you set a default to handle exceptions

edit: i think i know what you mean, you cant make it compare to variables, thats true

ModThe Djinn2 votes

Basically, a Switch statement is often more efficient and cleaner to read when you want to check a single value condition at a time (such as "X=1"). It can't handle comparisons to variables: it only handles comparisons to specific preset values.

Else If can do everything a **Switch **can, but is often just messier and/or less efficient if you're using it for what a Switch does do.

More from General Discussion

More by Xeronator