[Solved] C programming switch case what is wrong?


If this is your exact code, then the following is wrong:

  • There is no opening brace past the declaration of main(). Therefore there is no function body and you’re code is now sitting in the middle of global namespace.
  • There is also not declaration of the variable n, therefore it too, will cause a compilation error.
  • Finally, there is no return value for main(), which while not a compilation error (unless warnings are sufficiently pedantic) it is a logic error and leaves the return value for main() with undefined behavior.

This works:

#include <stdio.h>
int main( int argc, char* argv[] )
{ // <<==== note: added opening curly brace

    int n=65; // <<==== note: added declaration of n

    switch ( 4*(n >= 100) + 2*(n >= 10) + (n <= 10) )
    {
        case 1: printf( "%d is less than 10\n", n); break;
        case 3: printf( "%d is equal to 10\n", n); break;
        case 2: printf( "10 < %d < 100\n", n); break;
        default: printf(" %d is not in an identified range\n", n); break;
    }

    return 0; // <<==== note: added return value
} // <<== note: added closing curly brace

I leave whether the actual expressions in your switch condition are correct or not to you (I don’t think they are, but I am not familiar with your assignment).

2

solved C programming switch case what is wrong?