Learn C++
#include "operators/op_special.hpp"

sizeof, Scope Resolution & Ternary in C++

//concept

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.

//how it works
1

sizeof is compile-time

sizeof(int) is typically 4; sizeof on an array gives total bytes. No runtime cost β€” the compiler substitutes a constant.

2

:: 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.

3

Ternary for tiny branches

std::string s = (n == 1) ? "item" : "items"; picks a value inline where an if/else statement would need four lines.

4

Keep ternaries shallow

One level is idiomatic; nested ternaries are a readability hazard most style guides ban β€” use if/else instead.

//example
#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;
}
Output
5, cool
1sizeof(arr) is 20 bytes total and sizeof(arr[0]) is 4, so the division counts 5 elements β€” computed entirely at compile time.
2temp > 25 is false for 22, so the ternary evaluates to "cool".
3Both results print on one line, showing a compile-time query and a run-time branch side by side.
//use cases
Counting static array elements portably with sizeof(arr)/sizeof(arr[0])
Reaching shadowed globals with ::x inside functions that reuse the name
Inline labels, defaults, and clamps with a single readable ternary
Allocating exactly sizeof(Record) bytes in serialization and FFI code

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself β€” building beats watching.