sizeof, Ternary & Comma 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 (malloc(n * sizeof *p)) and array-length math (sizeof arr / sizeof arr[0], valid only before decay). The ternary ?: is an expression-level if/else for tiny branches, and the comma operator evaluates left-to-right yielding the last value — mostly seen in for-loop headers.
Keep ternaries one level deep (nested ternaries are a readability hazard) and treat comma outside for-headers as a smell — sequence points are better expressed as separate statements.
sizeof is compile-time
sizeof(int) is typically 4; sizeof on an array gives total bytes. Zero runtime cost — the compiler substitutes a constant of type size_t.
Ternary for tiny branches
printf("%s\n", n == 1 ? "item" : "items"); picks a value inline where if/else would need four lines.
Comma sequences
for (i = 0, j = n - 1; i < j; ++i, --j) runs two counters — the legitimate home of the comma operator.
Don't nest ternaries
Two levels deep, rewrite as if/else — future readers (including you) will thank present you.
#include <stdio.h> int main(void) { int arr[5] = {0}; size_t n = sizeof arr / sizeof arr[0]; int temp = 22; printf("%zu, %s\n", n, temp > 25 ? "warm" : "cool"); 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.