Switch Argument Outside While Loop Execution Explained

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

Discussion Overview

The discussion revolves around a C programming code snippet that implements a stack using an array. Participants are examining the behavior of a switch statement located outside a while loop and addressing issues related to case execution, uninitialized pointers, and the overall structure of the code.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • Some participants note that the switch statement should include break statements to prevent fall-through behavior between cases.
  • One participant points out that the choice input occurs outside the while loop, suggesting that the same choice is executed repeatedly without prompting for new input.
  • Concerns are raised about the uninitialized pointer 'top', which could lead to dereferencing garbage values when pushing or popping elements from the stack.
  • There is confusion regarding why only one case executes despite the presence of a while loop, with some participants asserting that without breaks, all cases should execute.
  • Clarifications are requested about the behavior of uninitialized pointers and their implications in the code.

Areas of Agreement / Disagreement

Participants express differing views on the execution behavior of the switch statement and the necessity of break statements. There is no consensus on the exact reasons for the observed behavior, and multiple interpretations of the code's execution remain present.

Contextual Notes

Limitations include the uninitialized state of the pointer 'top', which affects the stack operations, and the structure of the switch statement that may lead to unexpected behavior without proper breaks.

Who May Find This Useful

Readers interested in C programming, particularly those learning about control structures, pointers, and stack implementations, may find this discussion relevant.

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
4K
  • · 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