I have a file that has many #define statements such as –
#ifndef UTILITY_H
#define UTILITY_H
#define BUMP 7;
#define WHEEL_DROPS 7;
#define WALL 8;
#define CLIFF_LEFT 9;
#define CLIFF_FRONT_LEFT 10;
#define CLIFF_FRONT_RIGHT 11;
#define CLIFF_RIGHT 12;
#define VIRTUAL_WALL 13;
...
...
#endif
The list goes on to about 42 different values. I include this file into my other files, but whenever I try to use one of these constants I get errors. For a specific example, I try to do –
Sensor_Packet temp;
temp = robot.getSensorValue(BUMP); //line 54
cout<<temp.values[0]<<endl;
The errors I get are –
main.cpp:54: error: expected ‘)’ before ‘;’ token
main.cpp:54: error: expected primary-expression before ‘)’ token
main.cpp:54: error: expected ‘;’ before ‘)’ token
I don’t see why I am getting these errors because BUMP is already defined. This also happens when I try to use a switch statement with the cases being the defines –
switch(which) {
case BUMP:
//do stuff
case CLIFF_LEFT:
//do stuff
}
Is there something I am leaving out about using #define? I thought all I had to do was define a constant and then I could just call it. Any help is appreciated.
Take a closer look at your
#defines:This tells the preprocessor to replace
BUMPwith7;. Note that the macro definition includes the semicolon!So your code actually looks like this to the compiler:
Which are clearly syntax errors. To fix this, remove the semicolons in your
#definestatements.But in C++, you should be using
const ints orenums for constants instead of#defines. Here are some possible examples:This way is preferable because unlike
#defines,const ints andenums respect scope and are more type-safe.