1

Hello everyone I want to ask a question about including guards in C programming. I know their purpose but in some programms I have seen a 1" written after #define like this:

#ifndef MYFILE_H
#define MYFILE_H 1

What is the purpose of this 1? Is it necessary?

Penguin9
  • 481
  • 13
  • 23
mainajaved
  • 7,905
  • 10
  • 36
  • 44

3 Answers3

6

It's not necessary, #define MYFILE_H should do the trick. The fact that MYFILE_H is defined (the condition tested by ifndef) is separated from its value. It could be 0, ' ', 42, etc.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
2

It is not necessary if the MYFILE_H macro is not used elsewhere in your code.

If it is used elsewhere with an #ifdef or #ifndef directive like here:

#ifdef MYFILE_H 

then the 1 is not required in the macro definition-

but it if it used elsewhere with an #if directive like here:

#if MYFILE_H

then the 1 (or any value != 0) is required in the macro definition.

Note these directives could be used in a source file to verify if the header is included or not.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Sir does this also mean that we can use same named macro in both include guard and #if directive at the same time ? and differentiate by using only "1" or any number in include guard ? – mainajaved Jan 18 '12 at 18:26
  • @mainajaved a preprocessor directive in a source code can be used to check if the the header is included or not just by checking if the header guard macro is defined or not. If the header guard macro was defined with the `1`, it can be checked with both `#ifdef` or `#if` directive otherwise only with the `#ifdef` directive. – ouah Jan 18 '12 at 18:33
  • b-but why does it need it? – Penguin9 Oct 20 '20 at 03:44
0

It's a style thing, as far as i know. That '1' is unnecessary in my opinion; it doesn't really do anything.

Woodrow Douglass
  • 2,605
  • 3
  • 25
  • 41