开发者

Can you use #defined values in if statements (In C programs)?

开发者 https://www.devze.com 2022-12-28 23:41 出处:网络
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 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(CurrentPosi开发者_如何学JAVAtion >= STEPS_PER_REV)
{
    // do some stuff here
}

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


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.


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.


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.


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.


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


#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.

0

精彩评论

暂无评论...
验证码 换一张
取 消