Skip to content

Instantly share code, notes, and snippets.

@disconnect3d
Last active June 15, 2016 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disconnect3d/017b9642c9066d339d33046c69926380 to your computer and use it in GitHub Desktop.
Save disconnect3d/017b9642c9066d339d33046c69926380 to your computer and use it in GitHub Desktop.

Stackoverflow topics about const vs #define in C/C++:

Below an example of switch statement used with const variables in C and C++.

C:

dc@dc:/tmp$ cat test.c && gcc test.c
#include <stdio.h>

const int a1 = 1;
const int a2 = 2;

int main(int argc, char* argv[]) {
    switch(argc) {
        case 0:
            puts("ZERO");
            break;
        case a1:
            puts("1");
            break;
        case a2:
            puts("2");
            break;
    }
}
test.c: In function ‘main’:
test.c:11:9: error: case label does not reduce to an integer constant
         case a1:
         ^
test.c:14:9: error: case label does not reduce to an integer constant
         case a2:
         ^

C++:

dc@dc:/tmp$ cat test.cpp && g++ test.cpp && ./a.out
#include <stdio.h>

const int a1 = 1;
const int a2 = 2;

int main(int argc, char* argv[]) {
    switch(argc) {
        case 0:
            puts("ZERO");
            break;
        case a1:
            puts("1");
            break;
        case a2:
            puts("2");
            break;
    }
}
1
dc@dc:/tmp$ 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment