skip to content

Core Language Rules

The arithmetic types, the many ways to initialize a variable, operator rules, casts and auto: the grammar under every C++ answer, and the surprises interviewers open with.

on this pageshow

explore

questions

25

In C++, what does each of static_cast, const_cast and reinterpret_cast permit, and which one restores a callback's void* user data?

level: juniorimportance: must knowfreq 72%

answer

  1. one cast, one family of conversions
  2. inverse of the implicit T* to void*
  3. qualifiers only
  4. addresses and integers, never values

basics

~10 s

static_cast performs conversions the compiler understands, including void* back to the original T*; const_cast only adds or removes const and volatile; reinterpret_cast reinterprets pointers and integers. static_cast restores void* user data.

solid answer

~40 s

Each named cast permits one family of conversions and rejects the rest. `static_cast` does conversions the compiler can reason about: numeric ones, hierarchy casts without a run-time check, explicit constructors, and `void*` back to an object pointer, but it never removes `const`. `const_cast` changes only `const` and `volatile` qualifiers. `reinterpret_cast` converts between unrelated pointer types, pointers and integers, and function pointer types; it never converts a value such as a `float`, and it cannot drop `const`. For a C callback's `void* user`, `static_cast<Session*>(user)` is the right cast: it is the inverse of the implicit `Session*` to `void*` conversion and gives back the original pointer, provided you cast to exactly the type that was stored.

code

cpp · 27 lines
cpp
#include <cstdio>

// Legacy C plugin interface
extern "C" {
typedef void (*on_data_fn)(void* user, const char* buf, int len);
void register_callback(on_data_fn fn, void* user) { fn(user, "PING", 4); }
void legacy_log(char* msg) { std::puts(msg); }   // never writes, but takes char*
}

struct Session {
    int packets = 0;
    void on_data(const char* buf, int len) {
        ++packets;
        legacy_log(const_cast<char*>(buf));      // drops const only; legacy_log just reads
        std::printf("%d bytes, packet %d\n", len, packets);
    }
};

extern "C" void trampoline(void* user, const char* buf, int len) {
    auto* self = static_cast<Session*>(user);    // void* back to the stored Session*
    self->on_data(buf, len);
}

int main() {
    Session s;
    register_callback(&trampoline, &s);          // Session* to void* is implicit
}

go deeper

for a junior

Recall the job of each cast: static_cast for ordinary conversions and void* back to T*, const_cast for qualifiers, reinterpret_cast for addresses.

for a middle

Explain why static_cast is the right inverse of an implicit T* to void* conversion and which conversions each named cast refuses.

for a senior

In C interop code, insist that void* user data is cast back to exactly the stored type, and treat each reinterpret_cast as needing a justification.

for a principal

Make named casts the only allowed form in the codebase, enforced by -Wold-style-cast as an error, with reinterpret_cast and const_cast flagged for review.

## Why C++ splits casting into named operators A C cast `(T)x` can mean several very different things: a value conversion, dropping `const`, or reinterpreting an address as another type. C++ keeps that syntax for compatibility, but adds **named cast operators**, each allowed to perform only one family of conversions. Writing the name says which family you meant, and the compiler rejects the line if the conversion falls outside it. There are four: `static_cast`, `const_cast`, `reinterpret_cast` and `dynamic_cast`. The last one checks a polymorphic type at run time and belongs with RTTI; this answer covers the other three. ## `static_cast`: conversions the type system can reason about `static_cast<T>(e)` performs conversions whose meaning the compiler knows from the types alone: - numeric conversions spelled out on purpose: `static_cast<int>(2.9)` is `2`, `static_cast<double>(n) / d` forces floating division; - **`void*` back to an object pointer**: the inverse of the implicit `T*` to `void*` conversion; - up and down a class hierarchy without a run-time check (`Base*` to `Derived*` is your promise that the object really is a `Derived`); - calls to a constructor or a conversion function, including an `explicit` one; - enumerations to and from integers, and anything to `void` to discard a value. It refuses to remove `const`: `static_cast<char*>(msg)` with `const char* msg` fails with "static_cast from 'const char *' to 'char *' is not allowed". ## `const_cast`: only qualifiers `const_cast<T>(e)` adds or removes `const` and `volatile` on a pointer or reference and changes **nothing else**. Its legitimate use is calling a legacy API that is not const-correct but does not write, such as `void legacy_log(char* msg)`. Whether writing through the result is allowed depends on the object, not on the cast; that is its own interview question. ## `reinterpret_cast`: addresses and bit-level views `reinterpret_cast<T>(e)` converts between **pointer and reference types that are unrelated**, between pointers and integers (`std::uintptr_t`), and between function pointer types. The draft lists its conversions exhaustively and adds "No other conversion can be performed explicitly using reinterpret_cast". It never converts a value such as a `float` to an `int` (`reinterpret_cast<std::uint32_t>(1.0f)` does not compile), and it cannot cast away `const` ("casts away qualifiers"). Converting a pointer to another object pointer type and back gives the original pointer, provided the intermediate type's alignment is no stricter; *using* the intermediate pointer to read the object is governed by the aliasing rule, covered with type punning. | Cast | Changes the type how | Typical legal use | |---|---|---| | `static_cast` | a conversion the compiler understands | `void*` to `Session*`, `double` to `int` | | `const_cast` | qualifiers only | pass `const char*` to a read-only `char*` API | | `reinterpret_cast` | reinterprets addresses | pointer to `std::uintptr_t`, function pointer types | ## The plugin callback A C plugin interface typically takes a function pointer and an opaque `void* user`. Passing `&session` as `user` converts `Session*` to `void*` implicitly; inside the callback, `static_cast<Session*>(user)` restores it. The standard guarantees the round trip: when a `void*` that came from a `T*` is converted back with `static_cast<T*>`, the result points to the original object. `reinterpret_cast<Session*>(user)` also works, because between object pointers it is defined as going through `void*` with `static_cast`, but it announces a riskier conversion than the one taking place, so reviewers prefer `static_cast` here. The guarantee covers **exactly the type that was stored**. If the plugin stored a `Derived*` and the callback casts the `void*` to a base class pointer, no base adjustment happens, which matters as soon as multiple inheritance is involved. ## Mistakes worth naming 1. Using a C-style cast in the callback: it compiles for every one of these cases, so a wrong conversion is not reported. 2. Using `reinterpret_cast` where `static_cast` would do: it widens what the compiler accepts without making the code safer. 3. Using `const_cast` to silence an error from an API that really writes: the write may then hit an object defined `const`. 4. Casting the `void*` to a different type than the one stored, typically a base class. 5. Treating "it compiled" as proof: every one of these casts compiles in the wrong place too; only the named form narrows what the compiler will accept. A practical bonus of the named forms is that they are **searchable**: grepping a ported plugin for `reinterpret_cast` and `const_cast` lists exactly the lines that need a second look, which no search for `(` can do.

  • Why not just use `reinterpret_cast<Session*>(user)` in the callback?
    Between object pointer types the standard defines `reinterpret_cast` as a `static_cast` through `void*`, so the result is the same here. The cost is in review: `reinterpret_cast` also accepts integer-to-pointer and unrelated-pointer conversions, so it hides mistakes that `static_cast` would reject, and it signals danger where there is none.
  • What goes wrong if the plugin stored a `Plugin*` and the callback does `static_cast<Listener*>(user)` for a base class `Listener`?
    A `void*` carries no type, so the conversion produces a `Listener*` with the same address the `Plugin*` had. With multiple inheritance the `Listener` subobject may sit at a different address, so the pointer is wrong and using it is undefined behaviour. Cast back to `Plugin*` first, then convert to `Listener*`.

  • static_cast can remove const if the target type is non-const.
  • reinterpret_cast<int>(3.7f) converts the float to an integer value.
  • const_cast creates a modifiable copy of the object.
  • A void* can be cast to any base class of the stored object safely.
  • Named casts are just verbose spellings of the same C cast.
open as a page

What does the C++ standard guarantee about the widths of int and long and the signedness of plain char?

level: juniorimportance: must knowfreq 70%

basics

~20 s

C++ fixes only minimum widths: short and int at least 16 bits, long 32, long long 64, and sizeof(char) is 1. Whether plain char is signed is implementation-defined, so exact-width code uses std::int32_t and its <cstdint> siblings.

open as a page

What value does a C++ local int hold after int x;, compared with int x{}; and a global int x;?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A local int x; is default-initialized, which for int means not initialized: its value is indeterminate and reading it is undefined behaviour before C++26. int x{}; value-initializes it to 0, and a global int is zero-initialized because it has static storage duration.

open as a page

In C++, why is `len >= 1 && (buf[0] >> 4) == 4` safe on an empty buffer, but not the `&` version?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Built-in && evaluates its left operand first and skips the right one when the left is false, so buf[0] is never read on an empty buffer. Bitwise & evaluates both operands in no fixed order and reads out of bounds.

open as a page

In C++, what do `auto`, `auto&` and `const auto&` deduce when initialized from a function returning `const Order&`?

level: juniorimportance: must knowfreq 72%

basics

~10 s

Plain auto deduces Order, dropping the reference and top-level const, so it copies. auto& deduces const Order&, keeping the referred-to const, and const auto& deduces const Order& too.

open as a page

In C++, what does `explicit` block on a constructor and on `operator bool`, and where does `explicit operator bool` still convert?

level: middleimportance: must knowfreq 60%

basics

~20 s

An explicit constructor is not used for copy-initialization or implicit conversions, only for direct-initialization and casts. An explicit operator bool converts only in explicit casts and contextual conversions such as if conditions, !, && and ||.

open as a page

Why does the C++ comparison -1 < 1u evaluate to false, and which rule picks the common type?

level: middleimportance: must knowfreq 70%

basics

~20 s

The usual arithmetic conversions convert both operands to one common type. int and unsigned int share a rank, so the int converts to unsigned and -1 becomes UINT_MAX (4294967295 for 32 bits), not less than 1.

open as a page

Why does C++ reject int width{1920 * 1.25}; while int width = 1920 * 1.25; compiles?

level: middleimportance: must knowfreq 65%

basics

~20 s

Braces mean list-initialization, which makes a narrowing conversion ill-formed. Converting a double to an int is always narrowing, even from a constant, so the braced form is rejected, while copy-initialization with = silently truncates 2400.0 to 2400.

open as a page

Why does std::vector<int> v{10, 20} hold two elements in C++ while std::vector<int> v(10, 20) holds ten?

level: middleimportance: must knowfreq 70%

basics

~10 s

Braces make overload resolution try initializer-list constructors first. vector<int>{10, 20} matches vector(initializer_list<int>) and stores 10 and 20, while vector<int>(10, 20) calls the count-and-value constructor and stores ten copies of 20.

open as a page

In C++, why does `for (const std::pair<std::string, Order>& e : book)` over a `std::map` copy every entry, and how does `auto` fix it?

level: middleimportance: must knowfreq 62%

basics

~20 s

A map's elements are std::pair<const std::string, Order>; the loop names a pair without const, so each iteration builds and binds a temporary copy. const auto& deduces the exact element type and binds to the entry itself.

open as a page

In C++, when is writing through a pointer obtained with `const_cast` well-defined, and when is it undefined behaviour?

level: middleimportance: should knowfreq 52%

basics

~20 s

Writing through a const_cast result is defined only when the object itself was not created const; const_cast merely removes const from the access path. Modifying an object defined const, such as a const variable or a string literal, is undefined behaviour.

open as a page

What does a C-style cast `(T)expr` actually do in C++, and why can it silently become a reinterpret_cast?

level: middleimportance: should knowfreq 55%

basics

~10 s

A C-style cast tries const_cast, static_cast, static_cast plus const_cast, reinterpret_cast, then reinterpret_cast plus const_cast, and uses the first that applies. When no static_cast exists, it quietly reinterprets the address instead of failing.

open as a page

Why does a C++ float holding 0.1f compare unequal to the literal 0.1, and how should floating values be compared?

level: middleimportance: should knowfreq 45%

basics

~20 s

The literal 0.1 is a double, so the float is converted to double before ==. 0.1f widened is 0.10000000149011612, not the double nearest 0.1, so they differ. Compare floats against float literals, and compare computed values with a tolerance.

open as a page

In C++, what type does adding two std::uint16_t sensor readings produce, and why can the result surprise you?

level: middleimportance: should knowfreq 50%

basics

~20 s

The sum has type int: integral promotion converts any type ranked below int to int when int can hold all its values. 65535 + 1 is therefore 65536, and only storing it back into a std::uint16_t wraps it to 0.

open as a page

Why does C++ treat Window w(WindowConfig()); as a function declaration, and how do you write it so it creates an object?

level: middleimportance: should knowfreq 55%

basics

~20 s

C++ resolves the ambiguity in favour of a declaration: WindowConfig() can be read as an unnamed parameter of type function returning WindowConfig, so w becomes a function. Window w{WindowConfig{}}; or Window w((WindowConfig())); declares an object instead.

open as a page

In C++, why does `std::cout << flags & 0x0F;` fail to compile, and what does `flags & ACK == ACK` silently test?

level: middleimportance: should knowfreq 50%

basics

~20 s

An overloaded << keeps the shift operator's precedence, above &, so the line parses as (std::cout << flags) & 0x0F and no & accepts a stream. == binds tighter than &, so flags & ACK == ACK tests flags & 1.

open as a page

With 32-bit int in C++20, which of `-1 << 3`, `1u << 32` and `u8 << 8` are well-defined, and what changed since C++17?

level: middleimportance: should knowfreq 42%

basics

~20 s

In C++20 -1 << 3 is -8 and u8 << 8 promotes u8 to int first, so both are defined; 1u << 32 is undefined because the count equals the width. Before C++20, left-shifting a negative value was undefined.

open as a page

In C++17, what do `auto a{1};`, `auto b = {1};` and `auto c{1, 2};` deduce, and what changed from C++14?

level: middleimportance: should knowfreq 50%

basics

~10 s

Since C++17, auto a{1} deduces int, auto b = {1} deduces std::initializer_list<int>, and auto c{1, 2} is ill-formed. In C++14 the standard deduced std::initializer_list<int> for both brace forms.

open as a page

In C++20, why does `std::bit_cast<std::uint32_t>(gain)` work where `reinterpret_cast<std::uint32_t>(gain)` does not compile, and what does bit_cast require?

level: seniorimportance: should knowfreq 45%

basics

~10 s

reinterpret_cast converts addresses, pointers and integers, never a float value, so the value form is ill-formed. std::bit_cast (C++20) copies the bits into a new object and needs equal sizes and trivially copyable types.

open as a page

A C++ sensor logger validates network input with len <= buf.size() - offset, where offset and len are int; why do hostile packets pass, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

buf.size() returns std::size_t, so the int offset converts to unsigned and the subtraction wraps: an offset past the end or a negative one makes buf.size() - offset exceed the buffer, so bad lengths pass. Reject negatives first, then compare in one signedness.

open as a page

In a C++20 code review, which rules decide whether WindowConfig{.title = "Game", .width = 1920} compiles, and what do the members it omits get?

level: seniorimportance: should knowfreq 40%

basics

~10 s

It is ill-formed: C++20 designators must name members in declaration order, and title comes after width. Designated initializers work only on aggregates; omitted members use their default member initializer or are copy-initialized from {}.

open as a page

Since C++17, why does `std::cout << cur.next() << cur.next()` read bytes in order while `make_header(cur.next(), cur.next())` may not?

level: seniorimportance: should knowfreq 48%

basics

~20 s

C++17 sequences the left operand of << before the right one, also for overloaded stream operators, so the chain reads left to right. Function arguments are only indeterminately sequenced: they never interleave, but either may run first.

open as a page

In C++, why do `decltype(x)` and `decltype((x))` differ, and how does `decltype(auto)` make `return (local);` return a dangling reference?

level: seniorimportance: should knowfreq 45%

basics

~20 s

decltype of a plain name gives the variable's declared type, but a parenthesized name is an lvalue expression, so decltype((x)) is int&. decltype(auto) applies that rule to return (local);, returning a reference to a dead local.

open as a page

As a C++ lead, would you standardise on signed or unsigned integers for sizes and indices, and where do fixed-width types belong in your APIs?

level: principalimportance: should knowfreq 30%

basics

~20 s

Either can work: containers use unsigned std::size_t, while signed indices make subtraction safe and overflow detectable. Pick one rule, convert at named boundaries with checks, enforce it with warnings, and keep fixed-width types for layouts that leave the process.

open as a page

Should a C++ trading-gateway codebase adopt 'almost always auto' for locals, and where should explicit types remain mandatory?

level: principalimportance: should knowfreq 35%

basics

~20 s

Adopt auto as the default for locals where the type is evident or unnameable, since it forces initialization and avoids silent conversions, but keep explicit types for numeric domain values, public interfaces, intended conversions and proxy-returning expressions.

open as a page