sizeof, Scope Resolution & Ternary in C++
Beyond arithmetic live C++'s signature operators. sizeof reports a type's or object's byte size at compile time β the foundation of portable allocation and array-length math (sizeof(arr)/sizeof(arr[0])). The scope-resolution operator :: reaches into namespaces (std::cout), classes (MyClass::method), and the global scope (::x) to name exactly which entity you mean.
The ternary ?: is an expression-level if/else: cond ? a : b evaluates to a or b. It shines for tiny branches (labels, clamps, pluralization) but nests terribly β two levels deep, rewrite it as statements.
sizeof is compile-time
sizeof(int) is typically 4; sizeof on an array gives total bytes. No runtime cost β the compiler substitutes a constant.
:: disambiguates scope
std::string picks the library string, Config::load calls a class's static, and ::value grabs the global when a local shadows it.
Ternary for tiny branches
std::string s = (n == 1) ? "item" : "items"; picks a value inline where an if/else statement would need four lines.
Keep ternaries shallow
One level is idiomatic; nested ternaries are a readability hazard most style guides ban β use if/else instead.
#include <iostream>Β int main() { int arr[5] = {}; std::size_t n = sizeof(arr) / sizeof(arr[0]); int temp = 22; std::string feel = (temp > 25) ? "warm" : "cool"; std::cout << n << ", " << feel << std::endl; return 0;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.