views:

136

answers:

6

I am new at C programming. I thought when you type something like #define Const 5000 that the compiler just replaces every instance of Const with 5000 at compile time. Is that wrong? I try doing this in my code and I get a syntax error. Why can't i do this?

#define STEPS_PER_REV 12345

... in some function
if(CurrentPosition >= STEPS_PER_REV)
{
    // do some stuff here
}

The compiler complains about the if statement with a syntax error that gives me no details.

+2  A: 

Your code fragment is correct. #define is literally a string subsitution (with a bit more intelligence).

You can check what the preprocessor is doing in gcc by using the -E option, which will output the code after the pre-processor has run.

Yann Ramin
A: 

You are correct in that the C preprocessor will just replace STEPS_PER_REV with 12345. So your if statement looks fine, based on the code you provided.

To get to the bottom of this, could you please post your code and the actual contents of the error message.

Justin Ethier
A: 

You are right when you say that the compiler replaces every instance with the content of the macro. Check the type of CurrentPosition, probably the error is there.

Maurizio Reginelli
You might be on to something with the types. CurrentPosition is an unsigned long.
Jordan S
It should work with an unsigned long. I think you have to post a bit more of you code, otherwise it isn't simple to find the error.
Maurizio Reginelli
A: 

Yes, but that should be a const, not a macro. You probably getting the wrong type in your comparison.

Therealstubot
+9  A: 

the people in the comments are right. You almost definitely have a semicolon at the end of your #define. This means that your assignment becomes:

CURRENT_POSITION = 12345;;

(assuming that you HAD a semicolon at the end of the line...)

but your if becomes:

if(CurrentPosition >= 12345;)

which is of course invalid.

remember, #defines are NOT C code. They don't need semicolons.

Brian Postow
You're all right this was the problem!
Jordan S
A: 

#define in c are macros, they are used by c preprocessor to replace them when they're found. For example in your source code the

 **#define MAX_VALUE 500**

*if( reservations < **MAX_VALUE** )*
{
    ......
}

will be become into

*if( reservations < **500**)*
{
        ......
}

after preprocessing step. So that they could be used in boolean statetments in if sentences.

raullp