Is it possible to use #define inside a function?

前端 未结 6 1892
野性不改
野性不改 2021-01-07 22:38

For example, I saw source code like the following. Can we use #define in a function? How does it work? (more information: this code is what I copied from

6条回答
  •  抹茶落季
    2021-01-07 22:50

    #define is a preprocessor directive: it is used to generate the eventual C++ code before it is handled to the compiler that will generate an executable. Therefore code like:

    for(int i = 0; i < 54; i++) {
      #define BUFFER_SIZE 1024
    }
    

    is not executed 54 times (at the preprocessor level): the preprocessor simply runs over the for loop (not knowing what a for loop is), sees a define statement, associates 1024 with BUFFER_SIZE and continues. Until it reaches the bottom of the file.

    You can write #define everywhere since the preprocessor is not really aware of the program itself.

提交回复
热议问题