C++-Specific
Learn about good programming practices for C++ regarding code format, code structure, types, and constants.
We'll cover the following
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:
- C++ Core Guidelines by Bjarne Stroustrup and Herb Sutter
- Google C++ Style
-
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 usingclang-format
.
Code structure
- Avoid statements of the form
using namespace foo
. This might potentially lead to name clashes (if, say, you implement your ownmin
method) that will, in turn, lead to bugs that are difficult to catch. Moreover, this violates the general principle of using namespaces. If you usestd::vector
andstd::cin
heavily in your program, instead of
using namespace std;
write
using std::vector;
using std::cin;
- Avoid using old-style
scanf
andprintf
. Instead, usestd::cin
andstd::cout
.
For compatibility reasons,iostream
synchronizes withstdio
(which makes it possible to use both interfaces for input/output). Turning it off makesstd::cin
andstd::cout
work several times faster.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.