Switch Argument Outside While Loop Execution Explained

  • Context:
  • Thread starter Thread starter Crystal037
  • Start date Start date
  • Tags Tags
    Switch
Click For Summary
SUMMARY

The forum discussion centers on a C program that improperly handles switch-case statements within a while loop. The primary issue identified is the lack of break statements, which causes the switch to execute all cases sequentially instead of stopping after the matched case. Additionally, the variable 'top' is declared as an uninitialized pointer, leading to potential access of garbage values when dereferenced. To resolve these issues, the user must prompt for input within the loop and ensure each case in the switch statement ends with a break.

PREREQUISITES
  • Understanding of C programming syntax and structure
  • Knowledge of switch-case control flow in C
  • Familiarity with pointers and memory management in C
  • Experience with debugging and error handling in C programs
NEXT STEPS
  • Implement break statements in switch-case structures to prevent fall-through behavior
  • Learn about initializing pointers in C to avoid undefined behavior
  • Research best practices for user input handling within loops in C
  • Explore debugging techniques for identifying and resolving runtime errors in C programs
USEFUL FOR

C programmers, software developers, and computer science students looking to enhance their understanding of control flow and memory management in C.

Crystal037
Messages
167
Reaction score
7
TL;DR
switch in c programming inside a while but argument of switch is outside the while
C:
#include<stdio.h>
#define MAX_SIZE 6
int pop(int a[]);
void push(int a[],int e);
int pal(int a[]);
int *top;
int stack[MAX_SIZE];
int main(){
    int choice,done=0,ele;
    printf("1.Push\t2.Pop\t3.Pal\t4.Exit\n");
    printf("Enter your choice:\t");
    scanf("%d",&choice);
    while(!done){
        switch(choice){
            case 1:printf("\nEnter the element to be pushed\n");
            scanf("%d",&ele);
            push(stack,ele);
           
            case 2: if(pop(stack)==-1)
            printf("\nStack is empty\n");
            else{
             printf("\nDeleted Element=%d",pop(stack));
                }
           
            case 3:done=1;
          
            default:printf("\nInvalid Choice\n");
        }
    }
}
void push(int a[],int e){
    if(*top==MAX_SIZE-1){
        printf("\nStack Overflow\n");
    }
    else{
        a[++*top]=e;
    }
}
int pop(int a[]){
    if(*top==-1){
        printf("\nStack Underflow\n");
        return -1;
    }
    else{
        return a[*top--];
    }
}
Here switch argument is taken outside while loop so the argument of switch should remain constant and and that case should be in a loop then why is it executing only 1 time
 
Last edited by a moderator:
Technology news on Phys.org
because the case statements should end with a break:

[CODE lang="c" title="switch in C"]switch (choice) {
case 1:
// do something
break;
case 2:
// do something else
break;
default:
// do something defaulty
break; // <-- not sure if this last break is necessary
}[/CODE]
 
  • Like
Likes   Reactions: valenumr
I see several problems with this code, aside from the missing break statements for each case in the switch.
  1. The input to select a choice is done outside the while loop, so whatever the first choice is, that's the one that gets performed inside the loop. You need to prompt the user to enter the choice inside the while loop.
  2. The top variable is an uninitialized pointer. If the first choice is to push a value, the code attempts to dereference top, which is pointing to some garbage location.
There might be more problems, but these need to be addressed first.
 
Ev
Arjan82 said:
because the case statements should end with a break:

[CODE lang="c" title="switch in C"]switch (choice) {
case 1:
// do something
break;
case 2:
// do something else
break;
default:
// do something defaulty
break; // <-- not sure if this last break is necessary
}[/CODE]
Even if the break isn't the switch will execute all the cases. Doesn't explain why is it executing only one time.
 
Crystal037 said:
Ev
Even if the break isn't the switch will execute all the cases. Doesn't explain why is it executing only one time.
Yes it does: the switch will execute all the cases including the code after case 3.
 
Crystal037 said:
Even if the break isn't the switch will execute all the cases. Doesn't explain why is it executing only one time.
Your post is unclear. Without the break statements on each case, all four cases will execute.
pbuk said:
Yes it does: the switch will execute all the cases including the code after case 3.
To be clear, the snippet posted by Arjan82 that Crystal037 quoted doesn't have this problem.

@Crystal037, see my suggestions in post #3.
 
pbuk said:
Yes it does: the switch will execute all the cases including the code after case 3.
But when executing its only executing one case given like if I give option 1 it just executes 1 and doesn't go to 2 why and even if I put break in every statement bcz of while it should execute the choice entered before again and again bcz of the while loop
 
Mark44 said:
Your post is unclear. Without the break statements on each case, all four cases will execute.

To be clear, the snippet posted by Arjan82 that Crystal037 quoted doesn't have this problem.

@Crystal037, see my suggestions in post #3.
Thats what it should do but all the cases are not getting executed only the choice entered that's getting executed.
Also can u please explain the uninitialised pointer and how does it work.
 
Crystal037 said:
But when executing its only executing one case given like if I give option 1 it just executes 1 and doesn't go to 2 why and even if I put break in every statement bcz of while it should execute the choice entered before again and again bcz of the while loop
Is that code that you're running exactly the same as what is shown in post #1? If the code doesn't have break statements in each case, and you enter 1 as your choice, it will execute all three cases.

Crystal037 said:
Also can u please explain the uninitialised pointer and how does it work.
In line 6 you declare top
C:
int *top;
This means that top is a pointer, but it is uninitialized, so it doesn't contain the address of any known variable.
In lines 32 and 40 (in the bodies of the push() and pop() functions) you have
C:
void push(int a[],int e){
    if(*top==MAX_SIZE-1){                // line 32
.
.
.
int pop(int a[]){
    if(*top==-1){                             // line 40
In both lines you are dereferencing top, but since it was never initialized, you are getting access to garbage values.
 
  • Like
Likes   Reactions: sysprog
  • #10
@Crystal037, you posted this question on Tuesday and it's now Sunday evening. Are you making any progress on your program?
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 5 ·
Replies
5
Views
2K
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
Replies
8
Views
3K
  • · Replies 18 ·
Replies
18
Views
9K
  • · Replies 22 ·
Replies
22
Views
6K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
3
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K