banco popular english contact


Quora uses cookies to improve your experience. Read more

C++ (programming language)

C (programming language)

Programming Languages

Computer Programming

What is the use of switch statements in C programming?

Get to the root cause of Java performance issues.
Datadog APM provides distributed tracing and real-time analytics for Java apps. Free 14-day trial.
Learn More at datadoghq.com
10 Answers

Bharat Kumar

Bharat Kumar , Experience of different programming languages

Though the function of switch case and  else if ladder is same, there are a number of remarkable difference  between switch case and else if ladder in many aspects such as memory  consumption, speed of processing, variable requirement, comfort in  programming etc. Appropriate choice between switch case and if else  ladder is essential for the sake of ease, comfort, accuracy and  efficient programming.
Else If Ladder:
else if statement can be defined as a control statement which controls the  statement(s) to be executed on the basis of some conditions. Whenever  the else if statement is used, the compiler or interpreter initially  checks the condition whether it is true or false and if the condition is  found to be true then, the corresponding statements are executed. If  the condition is found to be false, it continues checking the next else if statement until the condition comes to be true or the control comes to the end of the else if ladder.
The syntax of else if ladder can be represented as:

if( condition-1)    
statement-1; 
else if (condition-2)    
statement-2; 
else if (condition-3)    
statement-3; 
else if (condition-4)    
statement-4; 
else if (condition-n)    
statement-n; 
else    
default statement;

  1. if( condition-1)
  2.    statement-1;
  3. else if (condition-2)
  4.     statement-2;
  5. else if (condition-3)
  6.     statement-3;
  7. else if (condition-4)
  8.     statement-4;
  9. else if (condition-n)
  10.     statement-n;
  11. else
  12.     default statement;

Below is a flowchart that represents else if ladder.

 Flowchart for else if ladder

Features of else if ladder:

  • It evaluates an expression and then, the code is selected based on the true value of evaluated expression.
  • Each else if has its own expression or condition to be evaluated.
  • The variable data type used in the expression of else if is either integer or character.
  • The decision making of the else if is dependent on zero or non-zero basis.

Switch Case:
The switch case statement is similar to the else-if ladder as it provides multiple  branching or multi-conditional processing. But, the basic difference  between switch case and else if ladder is that the switch case  statement tests the value of variable or expression against a series of  different cases or values, until a match is found. Then, the block of  code with in the match case is executed. If there are no matches found,  the optional default case is executed.
The syntax of switch case can be represented as:
switch(expression)
    
case constant-1        
block-1;      
break;     
case constant-2        
block-2;        
break;     
case constant-3        
block-3;        
break;     
case constant-n        
block-n;            
break;     
default:        
default_block;
 
statement-x;

  1. switch(expression)
  2.     case constant-1
  3.         block-1;
  4.         break;
  5.     case constant-2
  6.         block-2;
  7.         break;
  8.     case constant-3
  9.         block-3;
  10.         break;
  11.     case constant-n
  12.         block-n;   
  13.         break;
  14.     default:
  15.         default_block;
  16. statement-x;

Below is a flowchart that represents switch case.

 Flowchart for switch case

Features of switch case:

  • The switch case statement evaluates the value of an expression and a block of code is selected on the basis of that evaluated expression.
  • Each case refers back to the original expression.
  • The data type that can be used in switch expression is integer type only.
  • Each case has a break statement.
  • The switch case takes decision on the basis of equality.

Difference between switch case and else if ladder:
So,  after going through the two control statements in brief, here are the  main difference between switch case and else if ladder:

  1. In else if ladder,  the control goes through the every else if statement until it finds  true value of the statement or it comes to the end of the else if  ladder. In case of switch case, as per the value of the switch, the control jumps to the corresponding case.
  2. The switch case is more compact than lot of nested else if. So, switch is considered to be more readable.
  3. The use of break statement in switch is essential but there is no need of use of break in else if ladder.
  4. The  variable data type that can be used in expression of switch is integer  only where as in else if ladder accepts integer type as well as  character.
  5. Another difference between switch case and else if ladder is that the switch statement is considered to be less flexible than the else if ladder,  because it allows only testing of a single expression against a list of  discrete values.
  6. Since the compiler is capable of optimizing the  switch statement, they are generally considered to be more efficient.  Each case in switch statement is independent of the previous one. In  case of else if ladder, the code needs to be processed in the order  determined by the programmer.
  7. Switch case statement work on the basis of equality operator whereas else if ladder works on the basis of true false( zero/non-zero) basis.

Your feedback is private.
Is this answer still relevant and up to date?
Starting a new project? Get started for free.
Scale your deployments with a flexible and predictable pricing model. Free for 60 days.
Learn More at try.digitalocean.com

Karthika NM

Karthika NM , Passionate Programmer

Switch statements are used when you clearly know what are possible values for the condition variable.
Each value in that list of possible value is called case.
When the value given in input matches the value in the case statement, the block of code below case gets executed until it reaches the break statement.
Break is optional. If break statement is not given, the next case statement (if any) will also get executed.

for example, consider the following code:

#include <stdio.h>
 int main ()

 char grade = B;
   switch(grade)  
   case A :
             printf("Excellent!\n" );
             break;
   case B :
             printf("Well done\n" );
   case C :
              printf("Good\n" );
              break;
   case D :
              printf("You passed\n" );
              break;
   case F :
             printf("Better try again\n" );
             break;
   default :
              printf("Invalid grade\n" );
  
   printf("Your grade is  %c\n", grade );
     return 0;

The output of the above program is :
Well done
Good
Your grade is B

The value of the variable passed to the switch statement is checked against the case statements.
Case B matches. Hence the printf() executed. (Well Done – printed).
As there is no break statement, the next case C also executed. (Good – printed). As there is break statement, the statement after the switch is executed. Therefore Your grade is B – printed.

An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions. Once the condition is true, other conditions are not validated.
In switch case, mostly constant values are given in the condition while in if..else mostly boolean expressions are given.

for example,

#include <stdio.h>
int main ()

int a=10;
int b=20;

if (a>100)
   
     printf("Value of a is greater than 100");
   
elseif (b==20)
   
     printf("Value of b is 20");
    
elseif (a<100)
   
     printf("Value of a is less than 100");
   
else
  
    printf("Condition fails");
   
printf("Value of a is %d", a);
return 0;

Output of above program is:
Value of b is 20
Value of a is 10

The first if condition fails, so second if is checked.
The condition is true, so the statements inside that if gets executed.
The next if statements are not executed even if the condition is true.

Your feedback is private.
Is this answer still relevant and up to date?
MongoDB 4.0 supports multi-document ACID transactions.
See code samples, documentation, & deep dive demos from the engineers that built MongoDB transactions.
Learn More at mongodb.com

Isha Malhotra

Isha Malhotra , Software Developer (2010-present)

Switch Statement in C language

switch statement in c

Arun Kumar

Arun Kumar , C Programmer

  • The complexity of the program increases as the number of constants to compare increases. Switch statement provides a way to write easy to manage and readable code.
  • Switch statement [1] provides a default case handler when no case matches.
  • We can nest switch statements like if else statements.

Footnotes

[1] Switch Statement in C Programming

Harshit Gupta

Harshit Gupta , works at Decline To State

Switch is used for checking conditions.
Eg-
case 1:jTextField1.setText(hello);
break;
case 2:jTextField2.setText(hi);
In the example I have used Java GUI and have created a text field that user will enter a number 1 or 2 so if he enters 1hello will be printed and if he types 2 hi will be printed in the text field.
If is also used for the same thing, but there are advantages – you can enter range.
Eg- 80-90 etc.
And switch cases can only be applied on integer values only. String value cannot be used and I think it is very important data type.
So switch case has its limitations, and if-else case can overcome it.
I hope it helps , if it doesnt shoot a reply.

Neha Agarwal

Neha Agarwal , Trainer

Switch statement is a control statement that allows us to choose only one choice among the many given choices. The expression in switch evaluates to return an integral value, which is then compared to the values present in different cases. It executes that block of code which matches the case value. If there is no match, then default block is executed.

studytonight.com

  • Tutorials 

    PROGRAMMING

    Core Java

    C++

    C Language

    Network Programming

    Python

    Data Structure

    Android

    PHP

    Ruby

    Servlet

    JSP


    WEB

    HTML Course

    Web Playground

    CSS

    REST Web Service


    COMPUTER

    Computer Network

    Operating System

    Computer Architecture


    GAME DEVELOPMENT

    Game Development with Unity Engine


    DB

    DBMS

    MongoDB


    MISCELLANEOUS

    GIT

    Scrum Framework

    Jenkins

    Maven

    Apache Cordova

    Drools

  • Q & A Forum
  • Tests
  • HTML Course
  • Curious NEW
  • Sign in
     
WRITE
FOR US!
C LANGUAGE
  PRACTICE TESTS →

MenuSEE THE INDEX
  • Basics of C Language
  • Overview of C
  • Features of C
  • My First C program
  • Compile and Run C program
  • C Syntax Rules
  • Keywords and Identifier
  • Operators in C Language
  • Data Types in C
  • Variables in C
  • C Input / Output
  • Decision Making
  • Switch Statement
  • Looping
  • Arrays
  • string and character array
  • Storage classes
  • Functions in C
  • Introduction to Functions
  • Types of Functions and Recursion
  • Types of Function calls
  • Passing Array to function
  • Structures in C
  • All about Structures
  • Typedef
  • Unions
  • Pointers in C
  • Pointers concept
  • Declaring and initializing pointer
  • Pointer to Pointer
  • Pointer to Array
  • Pointer to Structure
  • Pointer Arithmetic
  • Pointer with Functions
  • Advanced Topics in C
  • File Input / Output
  • Error Handling
  • Dynamic memory allocation
  • Command line argument
  • C Programs
  • 100+ C Programs with explanation and output

Switch statement in C

When you want to solve multiple option type problems, for example: Menu like program, where one value is associated with each option and you need to choose only one at a time, then, switch statement is used.

Switch statement is a control statement that allows us to choose only one choice among the many given choices. The expression in switch evaluates to return an integral value, which is then compared to the values present in different cases. It executes that block of code which matches the case value. If there is no match, then default block is executed(if present). The general form of switch statement is,

switch(expression) case value-1:	block-1;	break; case value-2:	block-2;	break; case value-3:	block-3;	break; case value-4:	block-4; break; default: default-block;	break;

Rules for using switch statement

  1. The expression (after switch keyword) must yield an integer value i.e the expression should be an integer or a variable or an expression that evaluates to an integer.
  2. The case label values must be unique.
  3. The case label must end with a colon(:)
  4. The next line, after the case statement, can be any valid C statement.

Points to Remember

  1. We don’t use those expressions to evaluate switch case, which may return floating point values or strings or characters.
  2. break statements are used to exit the switch block. It isn’t necessary to use break after each block, but if you do not use it, then all the consecutive blocks of code will get executed after the matching block.
    int i = 1;
    switch(i) case 1: printf("A"); // No break case 2: printf("B"); // No break case 3: printf("C"); break;

    A B C

    The output was supposed to be only A because only the first case matches, but as there is no break statement after that block, the next blocks are executed too, until it a break statement in encountered or the execution reaches the end of the switch block.

  3. default case is executed when none of the mentioned case matches the switch expression. The default case can be placed anywhere in the switch case. Even if we don’t include the default case, switch statement works.
  4. Nesting of switch statements are allowed, which means you can have switch statements inside another switch block. However, nested switch statements should be avoided as it makes the program more complex and less readable.

Example of switch statement

#include<stdio.h>
void main( ) int a, b, c, choice; while(choice != 3) printf("\n 1. Press 1 for addition"); printf("\n 2. Press 2 for subtraction"); printf("\n Enter your choice"); scanf("%d", &choice); switch(choice) case 1: printf("Enter 2 numbers"); scanf("%d%d", &a, &b); c = a + b; printf("%d", c); break; case 2: printf("Enter 2 numbers"); scanf("%d%d", &a, &b); c = a - b; printf("%d", c); break; default: printf("you have passed a wrong key"); printf("\n press any key to continue"); 

Difference between switch and if

  • if statements can evaluate float conditions. switch statements cannot evaluate float conditions.
  • if statement can evaluate relational operators. switch statement cannot evaluate relational operators i.e they are not allowed in switch statement.

  • ← Prev
  • Next →


  

What is Studytonight?

About Us

Authors

Collaborate

Testimonials

Contact Us

Suggest

Tutorials

Android

Core Java

C++

Data Structures

Python

Network Programming

DBMS & SQL

Servlet

More…

Tests

Core Java

Android

C++

DBMS

C Language

GATE 2018

More…

Learn to Code

HTML

CSS

Website Development

Interview Questions

Java Interview Question

C++ Interview Question

OS Interview Question

DBMS Interview Question

More…

 
 
 
 
 

© 2018 Studytonight.   All rights reserved.

DMCA.com Protection Status