0
Why ifndef and endif is needed in cpp?
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...
+ 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.
+ 1
To define it the first time when it has not been defined.
0
Then why to include #define in it?