#ifndef inside a function

Hi, I was checking out how #ifndef is working in a header files but couldn't think of away to actually check if they are not tried to include twice even with a guard.
So I decided to check how this #ifndef is working if I use it inside a function. Here is the code

This is working like I supposed it would work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#define _GUARD_

void guard() {
#ifndef _GUARD_
#define _GUARD_

	std::cout << "_GUARD_ was not defined\n";

#endif
}

int main(){

	for (int i = 0; i < 5; ++i) {
		guard();
	}

}


This is not working

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

void guard() {
#ifndef _GUARD_
#define _GUARD_

	std::cout << "_GUARD_ was not defined\n";

#endif
}

int main(){

	for (int i = 0; i < 5; ++i) {
		guard();
	}

}


So why is the 2nd example prints guard() message 5 times instead of just 1?
Last edited on
So why is the 2nd example prints guard() message 5 times instead of just 1?

compiler does not process macros, macros are processed by preprocessor and then compiler kicks in.

your 2nd example does not make sense, preprocessor will just remove the macros you defined and leave the function as it is.

compiler will then compile the file and function will be called 5 times in for loop.

in first example guard() function will be preprocessed as empty function. and compiler will then compile empty function. but loop will run anyway and call the function 5 times which does nothing.
Last edited on
> _GUARD_

Avoid identifiers of this kind.

Some identifiers are reserved for use by C ++ implementations and shall not be used otherwise; no diagnostic is required.

Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.

Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
Thank you guys, everything is clear now :)
Topic archived. No new replies allowed.