liveBook · Manning

Scalar

As explained in Modern C

A scalar is a C value or type representing a single non-aggregate value rather than a collection of components.

A number as a condition

for (size_t i = 0; i < 5; ++i) { if (i) { printf("element %zu is %g\n", i, A[i]); } } Here, i is used directly as the controlling expression. The value 0 is false; every nonzero value is true. This makes if (i) equivalent in meaning to if (i != 0) for a numerical value. section 3.1

A scalar is a C value or type representing one non-aggregate value rather than a collection of components. The scalar types used here include signed and unsigned integers, floating-point values, characters, booleans, strings, pointers, and size-related types. section 3.1

Scalar values have two especially practical roles:

  • They can control conditional execution: 0 represents logical false, and any value different from 0 represents logical true. section 3.1
  • They can be initialized with an expression convertible to the scalar type, optionally surrounded by braces: double a = 7.8; and double d = { 0 }; are valid forms. section 5.5
  • The default initializer {0} is valid for every object type that is not a variable-length array. section 5.5
Table 3.1. Scalar types used in this book (view table figure)

Level

Name

Other

Category

Where

printf

0 size_t   Unsigned <stddef.h> "%zu" "%zx"
0 double   Floating Built in "%e" "%f" "%g" "%a"
0 signed int Signed Built in "%d"
0 unsigned   Unsigned Built in "%u" "%x"
0 bool _Bool Unsigned <stdbool.h> "%d" as 0 or 1
1 ptrdiff_t   Signed <stddef.h> "%td"
1 char const*   String Built in "%s"
1 char   Character Built in "%c"
1 void*   Pointer Built in "%p"
2 unsigned char   Unsigned Built in "%hhu" "%02hhx"

Compare the scalar categories, headers, and printf conversions used for common C values. section 3.1

How Modern C covers it

How deep it goes
Defines scalar categories and truth rules, then demonstrates initialization, while deferring the full set of condition primitives.
Examples
Demonstrates scalar conditions with loop indices, scalar declarations, formatted output, and the {0} initializer.
What you can do after
Apply scalar values in C conditions and initialize scalar objects with convertible expressions or {0}.
How it connects
Connects scalar types to conditional expressions, initializers, aggregate types, arrays, and pointers.

Also explained in

Compare how 4 books explain scalar →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.