Why does the preprocessor directive in one function affect the compilation of another?

前端 未结 3 2084
温柔的废话
温柔的废话 2021-01-20 01:03

Following program compiles successfully and print 1000 without even calling a foo() function from our main() function. How is it p

3条回答
  •  被撕碎了的回忆
    2021-01-20 01:16

    As others have stated, #define is a preprocessor directive, not C source code. See Wiki here.
    Point being, in your code #define ans 1000 is not a variable definition, meaning that even if you were calling foo() in the main, you would still not be setting "ans" at runtime, because it is simply not a variable. It is just telling the preprocessor what to do with the "label" "ans", when it finds it in your source code.

    In this example, the main() will essentially be calling an empty foo() function:

    int main() 
    {
      foo();              // Calls an empty function
      printf("%d", ans);  // ans will have been substituted by 1000 by the time you start executing you code
      return 0;
    }
    

    The definition of "ans" will simpy not exist anymore by the time you start executing you main(). This is what the preprocessor does (in part). It finds all the #defines declared in your entire source code and tries to find places in your code where you have used these defines. If you have not used them, it moves on (don't care), if you have, it substitutes the label by the actual defined value.

提交回复
热议问题