Home > front end >  How to do switch case with return value in function with char in C programming?
How to do switch case with return value in function with char in C programming?

Time:11-22

I am new to C programming, trying to do an Assignment for my class. I am trying to return char value in this function while using switch case. As an example, if i were to to put 'a', i expect 'b' to come out as the output.

#include <stdio.h>

char *upgrade(char plan);

int main()
{
    char plan;
    printf("what is your plan \n");
    scanf("&s",&plan);
    upgrade(plan);
    printf("\n%s",plan);
}

char *upgrade(char plan)
{
    switch(plan)
    {
        case 'a':
            plan = 'b';
        case 'b':
            plan = 'c';
    }
    return plan;
}

Every time I try to do so, the error "[warning] reutrn makes pointed from integer without a cast" comes. What exactly happens and how do i fix it?

CodePudding user response:

There are a number of problems with the code as posted.

Here's a fixed version, with comments:

#include <stdio.h>

char upgrade(char plan); // Return just a char, no pointer.

int main(void) // use void for no arguments
{
    char plan;
    printf("what is your plan \n");
    if (scanf("%c",&plan) == 1) // use % (not &), single char, check return
    {
      plan = upgrade(plan);  // store the upgraded value
      printf("\nYour upgraded plan is: %c\n", plan); // print single character, not a string
    }
    return 0;  // main() returns int.
}

char upgrade(char plan)  // return plain char, no pointer
{
    switch (plan)
    {
        case 'a':
            plan = 'b';
            break;   // use break to prevent fall-through
        case 'b':
            plan = 'c';
            break;
    }
   return plan;
}

CodePudding user response:

scanf("&s",&plan);

you don't want &s but %c which is the format specifier for a char in scanf.

upgrade(plan);

you want

plan = upgrade(plan);

in order to alter the variable plan in main, but the prototype should be char upgrade(char plan); instead of char *upgrade(char plan); (return a char not a pointer to it)

Finally, put a break after the cases, otherwise:

    case 'a':
        plan = 'b';
        // there is a fallthrough to the next case
    case 'b':
        plan = 'c';
  • Related