-3

I am trying to do the following evaluation: In my header file (define value can change):

#define X ((void *) 0)

In my function:

uint8_t foo() {

   uint8_t value = 0;

#if ( X != 0 )
   value = 1;
#endif

   return value;
}

When I compile the code it throws the following errors:

#57: this operator is not allowed in a constant expression
#58: this operator is not allowed in a preprocessing expression

When I do operations to see if the DEFINE exists (or not) it works fine (#ifdef or #if defined(X)). But what I want is to be able to evaluate the value of X at compile time. Am I missing any flag or something I need to set in order to be able to make this work? I am using Green Hills compiler.

melpomene
  • 84,125
  • 8
  • 85
  • 148
mareiou
  • 404
  • 2
  • 11

1 Answers1

1

You can't use casts in #if expressions1. The preprocessor knows nothing about types. (And the only values supported by #if are simple integers, so pointers are right out.)

Just use a regular if statement:

if (X != 0) {
    value = 1;
}

The compiler will recognize that the condition is always true (or false, depending) at compile time.


1 Reference: ISO 9899:1999, 6.10.1 Conditional inclusion:

  1. The expression that controls conditional inclusion shall be an integer constant expression except that: it shall not contain a cast; [...]
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • In fact you *can* use casts in `#if` expressions, but not the particular one the OP tries to use. – John Bollinger Jan 19 '18 at 21:48
  • You can use any cast in a preprocessor expression as long as you understand it's compiled in context after the preprocessor step during compilation. – nicomp Jan 19 '18 at 21:57
  • @JohnBollinger My C99 says otherwise (in 6.10.1/1). – melpomene Jan 19 '18 at 23:16
  • @nicomp What do you mean by "preprocessor expression"? – melpomene Jan 19 '18 at 23:17
  • @melpomene, the current C standard is C2011. I quote its relevant provision (which happens to be numbered the same) in my own answer; it does not contain the prohibition against casts. – John Bollinger Jan 19 '18 at 23:24
  • @JohnBollinger Yeah, but C11 still converts unknown identifiers to `0`, so how can you even form a cast expression? – melpomene Jan 19 '18 at 23:25
  • You make an excellent point, and in practice, `gcc` agrees with you. It's not the final arbiter, of course, but it's a useful gauge. – John Bollinger Jan 19 '18 at 23:32