Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

#include<stdio.h>


void foo()
{
    #define ans 1000
}

int main() {

  printf("%d", ans);
  return 0;
}
like image 495
Shubham Bansal Avatar asked Dec 02 '22 12:12

Shubham Bansal


1 Answers

#defineis run by the preprocessor which is staged before the compiler. After the preprocessor is done, 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 actually get compiled.

The preprocessor is very important to make header files work. In them, you see this structure:

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

Without this, the compiler would complain if a header file is included more than once. You may ask why you would want to include a header file more than once. Well, header files can include other header files. Consider this macro, which is useful for debugging. It prints the name of the variable and then the value. Note that you would have to do a separate version for different types.

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

This is pretty versatile, so you may want to include it in a header file for own use. Since it requires stdio.h, we include it.

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

What happens when you include this file and also include stdio.h in you main program? Well, stdio.h will be included twice. That's why debug.h should look like this:

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

The file stdio.h has the same construct. The main thing here is that this is run before the compiler. The define is a simple replacement command. It does not know anything about scope or types. However, as you can see here, there is some basic logic built into it. Another thing that the preprocessor does is to remove all the comments.

You can read more about the C preprocessor here: http://www.tutorialspoint.com/cprogramming/c_preprocessors.htm

like image 117
klutt Avatar answered Dec 20 '22 08:12

klutt