[Solved] Why can’t i check the return of a function with a switch?


It can be done – however your function should be returning an int.

int foo(void) { return 1; }

int main(void)
{
    switch(foo()) {
    case 0:  
            printf("foo\n");
            break;
    case 1:  
            printf("bar\n");
            break;
    default:
            break;
    }   
    return 0;
}

As, can been seen this compiles and runs.

[09:36 PM] $ gcc -Wall -Werror switcht.c -o switcht
[09:36 PM] $ ./switcht 
bar
[09:36 PM] $

However, if your function returns anything other than int then it wont compile. For instance if foo() return float:

float foo(void) { return 1.0; }

Then:

[09:44 PM] $ gcc -Wall -Werror switcht.c 
switcht.c: In function ‘main’:
switcht.c:7:9: error: switch quantity not an integer
switch(foo()) {
     ^~~~~~
[09:44 PM] $

2

solved Why can’t i check the return of a function with a switch?