C language

  • Thread starter shauns87
  • Start date
  • #1
shauns87
14
0
What is the difference between switch statement and if statement?
 

Answers and Replies

  • #2
Borek
Mentor
28,998
3,659
Let's start from the very beginning. What are they used for? What is the syntax in each case?
 
  • #3
shauns87
14
0
Switch: tests the value of a given variable against a list of case values and when a match is found, a block of statements associated with that case is executed.

If Else: If the test value is true, then the true block statements following the if are executed.

Now, the point is that I feel that both are the same and can be used interchangeably.

Am i right?
 
  • #4
Grep
298
2
Here's something you can't do with a switch statement:

Code:
if (x > 10)
{
    // Do something
}
else if (x < 0)
{
    // Do something else
}
else
{
    // etc...
}

So not really interchangeable in quite a few cases. An if can do what a switch can (though maybe less clearly and possibly less easy for the compiler to optimize). But a switch can't do everything an if statement can.
 
  • #5
chiro
Science Advisor
4,797
133
Switch: tests the value of a given variable against a list of case values and when a match is found, a block of statements associated with that case is executed.

If Else: If the test value is true, then the true block statements following the if are executed.

Now, the point is that I feel that both are the same and can be used interchangeably.

Am i right?

Switch statement compares a result with specific values. The if statement is a more general test that allows you to use more general tests for each if statement and more any subsequent elseif statement.
 
  • #6
shauns87
14
0
wow, thanks!
 

Suggested for: C language

  • Last Post
Replies
6
Views
2K
  • Last Post
Replies
13
Views
2K
  • Last Post
Replies
1
Views
1K
  • Last Post
Replies
1
Views
5K
  • Last Post
Replies
2
Views
524
  • Last Post
Replies
1
Views
3K
  • Last Post
Replies
8
Views
866
Replies
8
Views
270
  • Last Post
Replies
0
Views
2K
  • Last Post
Replies
1
Views
2K
Top