0

Why ifndef and endif is needed in cpp?

17th Jul 2017, 3:55 AM
Namra Khaleel
Namra Khaleel - avatar
4 Réponses
+ 1
Those are called #include guards. Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page. When the code is included again, the first ifndef fails, resulting in a blank file. That prevents double declaration of any identifiers such as types, enums and static variables. Also it prevents recursive inclusions... Imagine "alice.h" includes "bob.h" and "bob.h" includes "alice.h" and they don't have include guards...
17th Jul 2017, 4:01 AM
Oscar Albornoz
Oscar Albornoz - avatar
+ 1
To avoid re importing of header files. eg - #ifndef HEADER_FILE_H #define HEADER_FILE_H (header file code) #endif if the file "headerfile.h" is included again, all the code in the file is ignored as the macro HEADER_FILE_H is already defined. you can also use pragma once instead of ifndef nd endif.
17th Jul 2017, 4:04 AM
Nikunj Arora
Nikunj Arora - avatar
+ 1
To define it the first time when it has not been defined.
17th Jul 2017, 6:55 AM
Oscar Albornoz
Oscar Albornoz - avatar
0
Then why to include #define in it?
17th Jul 2017, 4:03 AM
Namra Khaleel
Namra Khaleel - avatar