Why the switch (0) does not lead to the warning, and what if (0)?

Given this code:

#include <stdio.h>

int main( int argc, char** argv )
{
    switch (0) { 
        case 1: printf("1"); 
        case 2: printf("2"); 
        default:
            printf("default");
            break; 
    }
    return 0;
}

I expect the compiler to tell me that something about the conditional expression is constant ( switch (0)while VS2012 throws this warning for if(0)) or unreachable code ( case 1, case 2).

However, neither on ideone , nor on Visual Studio 2012, nor on the latest GCC, I get anything.

Why don't even worthy compilers complain here?

+4
source share
4 answers

I just tried it on CLANG with the extended warning turned on and received the following warning:

enter image description here

( ) , :

   case 1: printf("1"); 
+4

C 2011 standard:

5.1.1.3

1       ( ), , undefined . . 9)
9) , , , . , . .

.

, , switch if ...

6.8.4.1 if



1     if .
...
6.8.4.2 switch



1   switch . 2       switch case default , switch . 154)

3     case , case switch . switch default. ( switch default case , case switch.)
154) switch, case default, switch, , .

... .

; if switch, . if( 0 ) switch( 0 ) , - .

+3

clang -Weverything: , argc argv , switch(0), gcc.

, , . , :

int test(int l) {
    switch (1) {
    case 0: return 0;
    case 1: return 1;
    default: return -1;
}

.

EDIT: clang , , , ryyker , -Wunreachable-code . .

+1

Visual Studio 2013, :

  • C/++

if, .

enter image description here

+1

Source: https://habr.com/ru/post/1618135/


All Articles