Stackoverflow topics about const
vs #define
in C/C++:
-
http://stackoverflow.com/questions/1674032/static-const-vs-define-vs-enum
-
http://stackoverflow.com/questions/1637332/static-const-vs-define
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$