C != C++
Une page qui a vocation à lister les différences majeures et un peu piégeuses ou marrantes entre C et C++.
GCC et G++ n’ont pas la même gestion des const (qui dépend du compilateur) !
exemple :
snippy:const snippy$ which gcc |xargs ls -l lrwxr-xr-x 1 root wheel 7 Jan 8 01:28 /usr/bin/gcc -> gcc-4.0 snippy:const snippy$ which g++ |xargs ls -l lrwxr-xr-x 1 root wheel 7 Jan 8 01:28 /usr/bin/g++ -> g++-4.0 snippy:const snippy$ gcc const.c snippy:const snippy$ ./a.out 2 2 -1073743752 -1073743752 3 snippy:const snippy$ g++ const.cpp snippy:const snippy$ ./a.out 1 2 -1073743752 -1073743752 3
2,2,3 pour GCC contre 1,2,3 pour G++
“C-language ‘borrowed’ the keyword ‘const’ from C++, which didn’t exist in 1979″
kode
snippy:const snippy$ cat const.c
/* If an attempt is made to modify an object defined with a const-qualified
* type through use of an lvalue with non-const-qualified type,
* the behavior is undefined (depends on the compiler)
* */
#include <stdio.h>
int modify(const int x) {
int *y = (int*)&x;
*y = 3;
return x;
}
int main() {
const int a = 1;
int *b = (int*)&a;
*b = 2;
printf("%d %d \n%d %d \n%d \n", a, *b, &a, b, modify(a));
return 0;
}
snippy:const snippy$ cat const.cpp
#include <stdio.h>
int modify(const int x) {
int *y = (int*)&x;
*y = 3;
return x;
}
int main() {
const int a = 1;
int* b = (int*)&a;
*b = 2;
printf(”%d %d \n%d %d \n%d \n”, a, *b, &a, b, modify(a));
return 0;
}