Learn about good programming practices for C++ regarding code format, code structure, types, and constants.

Code format

  • Stick to a specific code style. Mixing various code styles in your programs makes them less readable. Select your favorite code style and always follow it. Recommended style guides are the following:

  • Be consistent. For example, either always put the opening curly bracket on the same line as the definition of a class or a function or never do it.

  • There are many ways of formatting C++ code, and there is no universal way at the same time. It is important to be consistent.
    A simple and reasonable way of achieving this is autoformatting your code using clang-format.

Code structure

  • Avoid statements of the form using namespace foo. This might potentially lead to name clashes (if, say, you implement your own min method) that will, in turn, lead to bugs that are difficult to catch. Moreover, this violates the general principle of using namespaces. If you use std::vector and std::cin heavily in your program, instead of
using namespace std;


using std::vector;
using std::cin;
  • Avoid using old-style scanf and printf. Instead, use std::cin and std::cout.
    For compatibility reasons, iostream synchronizes with stdio (which makes it possible to use both interfaces for input/output). Turning it off makes std::cin and std::cout work several times faster.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.