Why are directives on top of header files included?

I was once told in a programming class that C ++ achieved better readability by letting a programmer declare his variable somewhere in a function block. So the variables were grouped together with the section of code that dealt with this.

Why aren't we doing the same for inclusion? In other words, why is it not recommended to put the included file next to the definition that actually uses it?

parser::parser()
{
  // some initialization goes there which does not make use of regex
}

#include <boost/regex.hpp>
parser::start()
{
  // here we need to use boost regex to parse the document
}
+5
source share
3 answers

, #include , , . , , , :

// Include on demand:
namespace ns {
   void f() {} // does not need anything
//... lots of other lines of code
#include <vector>
   void g() { std::vector<int> v; }
}

... . , ns, / ::ns::std::vector. , , ( ). , , ...

, . , , using namespace . , , using namespace, .

-. , f int double. (, int) , . , f(5.0) , , int - , - . ( , , , )

, , .

+8

:

#include <someheader>

namespace myns {
  void foo() {
  }

  void bar() {
    // call something from someheader:
    func();
  }
}

#include <someheader> . , :

namespace myns {
  void foo() {
  }
}

#include <someheader>

namespace myns {      
  void bar() {
    // call something from someheader:
    func();
  }
}

/ , , ( #ifdef s), . , .

, #include , , - :

namespace myns {
  void foo() {
  }

// Whoops, this shouldn't be inside myns at all!
#include <someheader>

  void bar() {
    // call something from someheader:
    func();
  }
}

- , <someheader>. ( , , UB, ODR, , , § 3.2.5).

+3

, . , , 99% .

, , . (, , ) , - , .

For the compiler, this does not matter.

0
source

All Articles