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 spec开发者_运维技巧ific 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 #define
s:
#define BUMP 7;
This tells the preprocessor to replace BUMP
with 7;
. Note that the macro definition includes the semicolon!
So your code actually looks like this to the compiler:
Sensor_Packet temp;
temp = robot.getSensorValue(7;);
cout<<temp.values[0]<<endl;
// ...
switch(which)
{
case 7;:
// do stuff
case 9;:
//do stuff
}
Which are clearly syntax errors. To fix this, remove the semicolons in your #define
statements.
But in C++, you should be using const int
s or enum
s for constants instead of #define
s. Here are some possible examples:
enum CliffPositions
{
CLIFF_LEFT = 9,
CLIFF_FRONT_LEFT = 10,
CLIFF_FRONT_RIGHT = 11,
CLIFF_RIGHT = 12,
};
enum WallType
{
WALL = 8,
VIRTUAL_WALL = 13;
}
const int BUMP = 7;
const int WHEEL_DROPS = 7;
// etc ...
This way is preferable because unlike #define
s, const int
s and enum
s respect scope and are more type-safe.
Remove the semi-colons and you should be good to go.
精彩评论