Home > Mobile >  How can we update the value of a global variable using switch statement in C?
How can we update the value of a global variable using switch statement in C?

Time:12-26

int mmak = 0;
int main(void)
{
    int marks[3] [3] = {{0,5,6}, {1,5,9}, {2,9,5}};
    for (int k = 0; k < 3; k  )
    {
        int sunk = marks[k] [0];
        switch (sunk)
        {
            case '0': mmak  ;
            break;
            case '1': mmak  ;
            break;
            case '2': mmak  ;
            break;
        }
    }
    printf("%i\n", mmak);
}

I want to update the value of global variable mmak. but the output I am still geting is 0. Can anyone help?

CodePudding user response:

Even if the issue is solved by removing single quoting of the clauses of your switch, I'd like to enrich this by adding some remarks:

  1. You should always consider a default case in a switch statement that covers unexpected situations.
  2. When you are printing an int you should use '%d' instead of '%i' for the reason explained here: ...difference between %d and %i ....
  3. Always end your main with a return [int]; statement.
#include <stdio.h>

int mmak = 0;

int main(void)
{
    int marks[3] [3] = {{0,5,6}, {1,5,9}, {2,9,5}};

    int sunk;

    for (int k = 0; k < 3; k  )
    {
        sunk = marks[k] [0];
        
        switch (sunk)
        {
            case 0:
                mmak  ;
                break;

            case 1:
                mmak  ;
                break;

            case 2:
                mmak  ;
                break;

            default:
                printf("No value found\n");
                break;
        }
    }
    printf("%d\n", mmak);
    return 0;
}

CodePudding user response:

case '2':

This case compares to the ASCII '2' (int 50), which is not the same as int 2. Instead use:

case 2:

The additional advice from comments for falling through cases will help when the same operation will be performed for more than one case:

case 0:
case 1:
case 2: mmak  ;
break;
case 3: mmak =2;
  •  Tags:  
  • c
  • Related