Skip to content

Instantly share code, notes, and snippets.

@weissi
Last active December 15, 2015 20:29
Show Gist options
  • Save weissi/5318320 to your computer and use it in GitHub Desktop.
Save weissi/5318320 to your computer and use it in GitHub Desktop.
Meaning of const
/* SAVE THIS FILE AS test.X */
#ifndef __cplusplus
# include <stdio.h>
# define PRINT_LANG printf("C\n");
#else
# include <iostream>
# define PRINT_LANG cout << "C++" << endl;
#endif
#ifdef __cplusplus
extern "C" {
namespace std {
#endif
int main(int argc, char **argv)
{
typedef struct {
int test_int;
} tst;
PRINT_LANG;
tst test = { 23 };
tst * vvv = NULL;
tst * const vvc = &test;
tst const * vcv = NULL;
tst const * const vcc = NULL;
const tst * cvv = NULL;
const tst * const cvc = NULL;
// const tst const * ccv = NULL; // ERROR: Double const --> vcv
// const tst const * const ccc = NULL; // ERROR: Double const --> vcc
vvv = &test;
#ifdef WITH_ERRS
vvc = &test; //ERROR
#endif
vcv = &test;
#ifdef WITH_ERRS
vcc = &test; //ERROR
#endif
cvv = &test;
#ifdef WITH_ERRS
cvc = &test; //ERROR
// ccv = &test; // --> vcv
// ccc = &test; // --> vcc
#endif
*vvv = test;
*vvc = test;
#ifdef WITH_ERRS
*vcv = test; //ERROR
*vcc = test; //ERROR
*cvv = test; //ERROR
*cvc = test; //ERROR
// *ccv = test; // --> vcv
// *ccc = test; // --> vcc
#endif
vvv->test_int = 42;
vvc->test_int = 42;
#ifdef WITH_ERRS
vcv->test_int = 42; //ERROR
vcc->test_int = 42; //ERROR
cvv->test_int = 42; //ERROR
cvc->test_int = 42; //ERROR
#endif
// ccv->test_int = 42; // --> vcv
// ccc->test_int = 42; // --> vcc
return 0;
}
#ifdef __cplusplus
}
}
#endif

Run them:

ln -s test.X test.c
ln -s test.X test.cpp

$ gcc -std=c99 test.c && ./a.out
C
$ clang -std=c99 test.c && ./a.out
C
$ g++ test.cpp && ./a.out
C++

Compare the errors:

$ diff -u <(clang -DWITH_ERRS test.c 2>&1 | grep -Eo ':[0-9]+:') <(g++ -DWITH_ERRS test.cpp 2>&1 | grep -Eo ':[0-9]+:') | wc -l
       0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment