Skip to content

Instantly share code, notes, and snippets.

@takehiko
Created August 7, 2014 14:03
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 takehiko/75522b72132d53d486d6 to your computer and use it in GitHub Desktop.
Save takehiko/75522b72132d53d486d6 to your computer and use it in GitHub Desktop.
Compare "const int", "#define", and "enum".
#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