Created
August 7, 2014 14:03
-
-
Save takehiko/75522b72132d53d486d6 to your computer and use it in GitHub Desktop.
Compare "const int", "#define", and "enum".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/* | |
constant.c - compare "const int", "#define", and "enum". | |
inspired by: | |
http://stackoverflow.com/questions/1674032/static-const-vs-define-in-c | |
*/ | |
/* gcc constant.c -o constant */ | |
/* gcc -std=c89 -pedantic -DOPTION_1 constant.c -o constant */ | |
/* gcc -g -DOPTION_1 -DUSE_DEBUGGER constant.c -o constant */ | |
/* gcc -DOPTION_2 constant.c -o constant */ | |
#if defined(OPTION_1) | |
static const int var = 5; | |
#elif defined(OPTION_2) | |
#define var 5 | |
#else | |
enum { var = 5 }; | |
#endif | |
void test_array(void) | |
{ | |
int array[var]; | |
int i; | |
printf("**** test_array ****\n"); | |
for (i = 0; i < var; i++) { | |
array[i] = i; | |
printf("array[%d] = %d\n", i, array[i]); | |
} | |
} | |
void test_switch(void) | |
{ | |
#if !defined(OPTION_1) || !defined(USE_DEBUGGER) | |
int i; | |
printf("**** test_switch ****\n"); | |
for (i = 0; i < 7; i++) { | |
switch (i) { | |
case var: | |
printf("i = %d\n", var); | |
break; | |
} | |
} | |
#endif | |
} | |
int main(void) | |
{ | |
test_array(); | |
test_switch(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment