When defining pointers in C/C++ you should be careful on how you use the * characters. If you try to define multiple pointers on the same line and you do not add the * character in front of each variable, then the results will not be what you would expect. In the following examples we added the * to the data type definition, hoping that all variables would become pointers of that data type. Unfortunately, as the compiler points out later on while making the comparisons, only the first variable in each line becomes a pointer of the data type.
Wrong Examples
C Source Code:
#include <stdio.h> int main() { int* a, b; int *c, d; int * e, f; a == b; c == d; e == f; return 0; }
Compiler Output:
$ gcc -o main *.c main.c: In function 'main': main.c:9:7: warning: comparison between pointer and integer a == b; ^ main.c:10:7: warning: comparison between pointer and integer c == d; ^ main.c:11:7: warning: comparison between pointer and integer e == f; ^
C++ Source Code:
#include <iostream> using namespace std; int main() { int* a, b; int *c, d; int * e, f; a == b; c == d; e == f; return 0; }
Compiler Output:
$ g++ -std=c++11 *.cpp -o main main.cpp: In function ‘int main()’: main.cpp:10:10: error: ISO C++ forbids comparison between pointer and integer [-fpermissive] a == b; ^ main.cpp:11:10: error: ISO C++ forbids comparison between pointer and integer [-fpermissive] c == d; ^ main.cpp:12:10: error: ISO C++ forbids comparison between pointer and integer [-fpermissive] e == f; ^
Correct Examples
#include <stdio.h> int main() { int* a, * b; int *c, *d; int * e, * f; a == b; c == d; e == f; return 0; }
#include <iostream> using namespace std; int main() { int* a, * b; int *c, *d; int * e, * f; a == b; c == d; e == f; return 0; }
This post is also available in: Greek