Coding Techniques
Basic Syntax and Data Types · Study material
Brace initialization catches narrowing
Copy initialization silently truncates; braces turn the same mistake into a compile error. Digit separators (C++14) make long literals readable.
#include <iostream>
int main() {
double price = 99.75;
int a = price; // silently drops .75 (compilers only warn)
int b = static_cast<int>(price); // same result, but clearly intended
// int c{price}; // error: narrowing conversion – caught at compile time
long long big{3'000'000'000}; // digit separators make large literals readable
std::cout << a << ' ' << b << ' ' << big << '\n';
return 0;
}
99 99 3000000000
Prefer constexpr for true constants
constexpr int max_students = 60; // known at compile time: usable as an array size
constexpr double pi = 3.141592653589793;
int seats[max_students]{}; // OK
const int today = read_day(); // const: fixed after initialization, value known at run time
// int list[today]; // error: not a constant expressionUse constexpr whenever the value is known while compiling; use const for values computed at run time that must not change. Avoid #define for constants – macros have no type and no scope.
Use auto where the type is obvious or long
auto count = 0; // int
auto ratio = 0.75; // double
auto it = scores.begin(); // std::map<std::string, int>::iterator – no need to spell it
auto name = std::string{"Asha"}; // std::string, not const char*
auto total = 0; // careful: int, even if you meant double
for (double s : prices) total += s; // fractions are lost Avoid integer overflow with wider types
int seconds_per_year = 365 * 24 * 60 * 60; // 31,536,000 – fits in int
int ms_per_year = 365 * 24 * 60 * 60 * 1000; // overflow! undefined behaviour
long long ms_ok = 365LL * 24 * 60 * 60 * 1000; // LL makes the whole product long long
auto bytes = std::int64_t{4} * 1024 * 1024 * 1024; // fixed width from <cstdint>The type of an expression is decided by its operands, not by the variable it is stored in. Make the first operand wide enough and the rest follow.
Compare floating-point values with a tolerance
#include <cmath>
bool nearly_equal(double a, double b, double eps = 1e-9) {
return std::fabs(a - b) <= eps * std::fmax(1.0, std::fmax(std::fabs(a), std::fabs(b)));
}
nearly_equal(0.1 + 0.2, 0.3); // true, although 0.1 + 0.2 == 0.3 is false Good C++ basics habits
- Initialize every variable where you declare it.
- Write
std::explicitly; never putusing namespace std;in a header. - Use
'\n'instead ofstd::endlunless you need a flush. - Use
static_cast, never C-style casts. - Prefer
std::int64_torlong longfor values that can exceed 2 billion. - Compile with warnings on:
-Wall -Wextra.