0

I have read that I am not able to include preprocessor directives inside my function. But when I implement it, it works. Here are my code:

#include <iostream>

#define MY_CONSTANT 41

void myFunction(int x) {

    #if x == 42
       std::cout << "Value is 42." << " "<<x<<std::endl;
    #else
       std::cout << "Value is not 42." <<" "<<x<< std::endl;
    #endif
                       }

int main() {
  myFunction(42);
  return 0;
           }

'The output was not like what I expected. It is: Value is not 42, 42. Could you explain me what really happened here. Why the directive come to the else statement.'

3
  • 2
    The preprocessor runs before the actual code is parsed. As such it have no idea about variables in the actual code, only defined macros. Commented Jan 24, 2024 at 15:48
  • You could as write #if adhfsgfhsfglkjn and get the same result. For preprocessor your x is simply not defined, so a whole condition evaluates to false. This could help you: stackoverflow.com/a/1643874/4165552 Commented Jan 24, 2024 at 15:53
  • 1
    The preprocessor does not know about x, so x == 42 is false. As such, by the time the code gets to the compiler, the function looks like void myFunction(int x) { std::cout << "Value is not 42." <<" "<<x<< std::endl; } Commented Jan 24, 2024 at 15:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.