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

After successfully compiling the program and printing 1000 without calling a function foo()from our function main(). How is this possible?

#include<stdio.h>


void foo()
{
    #define ans 1000
}

int main() {

  printf("%d", ans);
  return 0;
}
+4
source share
2 answers

#defineIt is started by the preprocessor, which is executed before the compiler. After the preprocessor is executed, the code will look like this:

/* Everything that is inside stdio.h is inserted here */

void foo()
{
}

int main() {

  printf("%d", 1000);
  return 0;
}

And this is what is actually compiled.

A preprocessor is very important for creating header files. In them you see this structure:

#ifndef foo
#define foo
/* The content of the header file */
#endif

, . , . , . , . , .

#define dbg_print(x)  fprintf(stderr, "%s = %x", #x, x)

, . stdio.h, .

/* debug.h */
#include <stdio.h>
#define dbg_print(x)  fprintf(stderr, "%s = %x", #x, x)

, , stdio.h ? , stdio.h . debug.h :

/* debug.h */
#ifndef DEBUG_H
#define DEBUG_H
#include <stdio.h>
#define dbg_print(x)  fprintf(stderr, "%s = %x", #x, x)
#endif

stdio.h . , . - . . , , . , , .

C : http://www.tutorialspoint.com/cprogramming/c_preprocessors.htm

+10

Source: https://habr.com/ru/post/1682040/


All Articles