YOUR C LEARNING COMPANION

Find your next idea.

CLEARER CONCEPTS

Make the tricky
ideas clearer.

Six focused guides for ideas that are easy to mix up. Compare them, follow a small example, and open the deeper rules when you need them.

Start with one idea. There is no score or required order. The guides are also available inside their chapters.

01PointersA pointer, its value, and its targetSeparate the pointer object from the object it lets you reach.

A pointer, its value, and its target

A pointer object stores a pointer value. A valid value can let an expression refer to another object. Changing the stored pointer value and changing the target are different actions.

When this helps Use this distinction when reading pointer assignments, shared access to an object, and functions that receive pointers.

Read the ideas side by side

Pointer object
The variable p has its own storage and a pointer type.
Pointed-to object
The int object left has separate storage and its own value.

Changing p does not, by itself, change left.

p = &right
Store a different pointer value in p.
*p = 6
Store 6 in the int object currently designated through p.

Read the left side first: which object is being changed?

Copy a pointer value
int *q = p gives q the value currently stored in p.
Copy a target value
int saved = *p reads an int value into a separate int object.

Neither operation makes q a live link to later changes of p.

Follow the reasoning

All objects below remain alive. Follow the named objects, without inventing numeric memory addresses.

C17 · illustrative fragments in the stated context

  1. int left = 4, right = 8;
  2. int *p = &left;
  3. int *q = p;
  4. p = &right;
  5. *q = 6;
  1. Create two int objects

    left starts at 4 and right starts at 8. Each object has its own stored value.

  2. Initialize p

    &left supplies a pointer to left. The declaration gives p that value.

  3. Initialize q from p

    q receives a copy of p’s current pointer value. Both values point to left.

  4. Redirect p

    p = &right changes p. q still points to left because q was not assigned again.

  5. Write through q

    *q = 6 changes left to 6. right remains 8; p points to right and q points to left.

Common misconceptions

These statements are misleading. Open each one to see why.

MisconceptionA copied pointer follows the original pointer variable.

The value is copied at that moment. To refer to the pointer object p itself, another pointer would need an appropriate pointer-to-pointer type.

MisconceptionA non-null pointer is always safe to dereference.

Non-null only excludes a null value. The target must still be alive, correctly aligned, and accessible through the expression’s type.

MisconceptionA cast repairs an invalid pointer.

A cast requests a type conversion. It does not create a live target object or grant access outside valid storage.

Go a little deeperOptional technical detail

A useful picture has limits

A box and arrow diagram shows a relationship. C does not require every pointer to be a simple numeric RAM address, nor every pointer type to share one size.

Pointer arithmetic has a separate contract

For object pointers, moving within an array or to its one-past position follows array rules. A one-past pointer cannot be used to access an element there.

C17 A null pointer can be represented using a null pointer constant in a suitable pointer context. Do not infer that every byte of a null pointer must be zero.

C23 C23 adds the null pointer constant nullptr; <stddef.h> names its distinct type nullptr_t. Conversion to a pointer type produces a null pointer. Lifetime, bounds, alignment, and access rules still apply.

Check the source rules

Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.

Say it in your own words

After p is redirected, why does writing through q still change left?

Compare with an explanation

q holds its own copied pointer value. Redirecting p does not assign a new value to q.

Read this guide in its chapter
02ArraysAn array is an object, not a pointer variableUnderstand the array, its first element, and the pointer an expression can produce.

An array is an object, not a pointer variable

An array contains a fixed number of elements of one type for that array instance. In many expressions its name is converted to a pointer to the first element. The conversion does not change the array object into a pointer object.

When this helps Use the distinction when finding a real array’s element count, passing array data to a function, and checking a subscript.

Read the ideas side by side

The array marks
marks has type array of 3 int. Its storage includes three int elements.
The pointer p
p has type pointer to int. It can be assigned a different pointer value.

An array expression often produces a pointer, but the two types are different.

sizeof marks
For this actual non-VLA array, this measures storage for all three elements.
sizeof p
This measures the pointer object, not the storage reachable through it.

The element-count formula needs the actual array, not a pointer parameter.

marks + 2
Points to the last element, which can be accessed while the array is alive.
marks + 3
Is the one-past position. It may mark an end but has no element to read.

A legal pointer position is not always a legal dereference position.

Follow the reasoning

This example uses an actual three-element array in one function. size_t is available from <stddef.h>.

C17 · illustrative fragments in the stated context

  1. int marks[3] = {3, 6, 9};
  2. size_t count = sizeof marks / sizeof marks[0];
  3. int *p = marks;
  4. int last = *(p + 2);
  5. int *end = marks + count;
  1. Initialize the array

    The elements marks[0], marks[1], and marks[2] hold 3, 6, and 9.

  2. Find the element count

    sizeof marks is three times sizeof marks[0], so the quotient is 3. No fixed byte size for int is needed.

  3. Initialize p

    In this initializer, marks converts to a pointer to its first element. p stores that pointer value.

  4. Access the last element

    p + 2 points to marks[2]. Dereferencing it reads 9.

  5. Form the end position

    marks + count is one past the array. The example forms and compares this pointer; it never dereferences it.

Common misconceptions

These statements are misleading. Open each one to see why.

MisconceptionThe array name is a pointer variable.

The array name designates the array object. Many uses convert its expression to a pointer value, but you cannot reassign the array itself with marks = p.

MisconceptionWriting int a[3] as a function parameter passes three copied elements.

An array parameter declaration is adjusted to a pointer parameter. The ordinary [3] spelling does not copy three elements or automatically carry their count.

MisconceptionAdjacent memory makes an out-of-range subscript valid.

Access must satisfy the array’s bounds. A nearby address or an apparently successful run does not create an extra element.

Go a little deeperOptional technical detail

The operator matters

For the actual array here, sizeof and unary & do not apply the usual array-to-pointer conversion. &marks has pointer-to-array type, while marks in the initializer for p produces pointer-to-int type.

Arrays of arrays keep their row type

For int grid[2][3], the usual conversion produces a pointer to a row of 3 int. It does not produce int **. Keep row bounds and the pointed-to type in the model.

C17 Array parameter adjustment and the one-past boundary apply in C17. Variable-length arrays have additional rules; this fixed-size example does not depend on them.

C23 C23’s typeof operators can preserve an array type instead of applying the usual conversion. Array parameters still adjust to pointer parameters; typeof on such a parameter sees its adjusted type.

Check the source rules

Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.

Say it in your own words

Why does the sizeof element-count formula work here but not for a pointer parameter?

Compare with an explanation

Here marks is the actual array. A pointer parameter has a pointer type, so sizeof measures that pointer rather than the caller’s array.

Read this guide in its chapter
03Scope & lifetimeWhere a name is visible and when an object existsKeep scope, lifetime, and storage duration in separate parts of your mental model.

Where a name is visible and when an object exists

Scope describes where an identifier can be used in source code. Lifetime describes when an object exists during execution. Storage duration supplies rules that determine that lifetime.

When this helps Use these questions when reading blocks, local static objects, recursion, and pointers that escape a function.

Read the ideas side by side

Scope
A source-code region in which a particular name can refer to its declared entity.
Lifetime
A period of execution in which an object exists and its storage is reserved.

A hidden name does not necessarily mean a dead object.

Automatic local fresh
A new object exists for each active call here. Its initializer supplies 0 when reached.
Static local total
One object lasts for the whole program and keeps its stored value between calls.

Both names have block scope; their objects have different storage durations.

Name and initializer
For fresh, scope begins just after its declarator in source. Its automatic initializer runs each time execution reaches the declaration.
Entering a block
For an ordinary non-VLA automatic object, lifetime begins on entry to its associated block.

Do not treat name visibility, lifetime start, and initialization as one event.

Follow the reasoning

Call visit twice in separate statements. The returned number puts total in the tens position and fresh in the units position.

C17 · illustrative fragments in the stated context

  1. int visit(void) {
  2. static int total;
  3. int fresh = 0;
  4. ++total;
  5. ++fresh;
  6. return total * 10 + fresh;
  7. }
  1. Before the calls

    The static object total already exists and is zero-initialized before program startup. Its name is only visible in its declared block.

  2. Start the first call

    A fresh automatic object belongs to this call. When its declaration is reached, its initializer stores 0.

  3. Increment and return

    total becomes 1 and fresh becomes 1. The function returns 11; that call’s fresh object ends when its block is left.

  4. Start the second call

    The same total object still holds 1. A new fresh object is initialized to 0 for this call.

  5. Increment again

    total becomes 2 and the new fresh becomes 1. The second result is 21. The two automatic objects never need to exist together here.

Common misconceptions

These statements are misleading. Open each one to see why.

MisconceptionAll local objects are created when their declaration line executes.

For ordinary non-VLA automatic objects, lifetime begins at block entry; the declaration can introduce the name and run initialization later. VLAs have different lifetime rules.

MisconceptionA local static object is created anew on every call.

The name has local scope, but the object has static storage duration. In this C example, initialization is not a C++-style first-call operation.

MisconceptionReturning a pointer extends a local object’s lifetime.

Returning a pointer value does not extend the pointed-to object’s lifetime. Do not access an ordinary local object after its function has returned.

Go a little deeperOptional technical detail

Scope is about identifiers

Objects can still be reached through valid pointers even when their own names are out of scope. An object’s lifetime must independently permit that access.

Avoid turning a model into a machine promise

“Stack local” is useful implementation vocabulary, not the C definition of automatic storage duration. C does not mandate one physical stack layout for these objects.

C17 The walkthrough uses ordinary automatic int objects and one zero-initialized static int. It excludes VLAs, longjmp, threads, and compound-literal lifetime details.

C23 The scope/lifetime distinction still applies in C23. New syntax does not make a pointer to an expired automatic object valid.

Check the source rules

Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.

Say it in your own words

Why does fresh return to 0 for the second call while total keeps 1?

Compare with an explanation

The second call has a new automatic fresh object whose initializer stores 0. The static total object continues to exist between calls.

Read this guide in its chapter
04Integer conversionsThe expression’s type comes before its destinationFollow operand types, the operation, and the final conversion in that order.

The expression’s type comes before its destination

C can convert values before an operation and again when storing its result. The destination type does not travel backwards and change an earlier operation.

When this helps Use this order when reading integer division, mixed signed/unsigned comparisons, casts, and assignments to smaller types.

Read the ideas side by side

Integer division
With a nonzero divisor and a representable quotient, int division produces an int result, discarding the fractional part toward zero.
Floating division
A floating operand can cause the other arithmetic operand to be converted before division.

A double destination alone does not make 5 / 2 a floating operation.

Implicit conversion
The language rules request a conversion at an operation, call, return, or assignment.
Explicit cast
The source explicitly requests a conversion to a named type.

An explicit conversion still follows rules and can lose information.

Integer promotion
Some integer types are converted to int or unsigned int before many operations.
Usual arithmetic conversions
For operators that use them, rules find a common arithmetic type after the applicable promotions.

“The largest-looking variable wins” is not the rule.

Follow the reasoning

Use only the two displayed int operands. This walkthrough assumes ordinary binary double arithmetic, where 2.5 is exactly representable.

C17 · illustrative fragments in the stated context

  1. int numerator = 5, denominator = 2;
  2. double first = numerator / denominator;
  3. double second = (double)numerator / denominator;
  1. Read the operand declarations

    numerator and denominator are int objects holding 5 and 2.

  2. Evaluate the first division

    Both operands are int, so numerator / denominator produces the int value 2.

  3. Initialize first

    The already-computed 2 is converted to double. first receives 2.0; the lost fraction cannot be recovered.

  4. Convert before the second division

    (double)numerator produces 5.0. For this division, denominator is converted to double as well.

  5. Initialize second

    The floating division yields 2.5 and initializes second. The cast’s position changes which operation is performed.

Common misconceptions

These statements are misleading. Open each one to see why.

MisconceptionThe left-hand type decides how the whole right side is calculated.

Evaluate the right-hand expression using its own operand types first. Then apply the conversion needed by the destination.

MisconceptionA cast proves that a value fits.

A cast requests conversion without checking a range for you. Check the relevant limits before converting when value preservation matters.

MisconceptionUnsigned always makes arithmetic safer.

Unsigned arithmetic has wraparound rules, but a wrapped count can still be logically wrong. Mixed signed/unsigned operations can also change a comparison’s meaning.

Go a little deeperOptional technical detail

Signed and unsigned of the same rank

For int and unsigned int in a usual arithmetic conversion, the common type is unsigned int. In -1 < 1U, -1 becomes UINT_MAX and the comparison is false. This does not modify the original int object.

Conversion is not signed overflow

Converting an integer to an unsigned type uses modular reduction. An out-of-range conversion to a signed integer type has an implementation-defined result or signal. Signed arithmetic overflow is a different rule: undefined behavior.

C17 The examples use standard int, unsigned int, and double rules. Do not assume an 8-bit byte or a 32-bit int when applying them elsewhere.

C23 C23 requires two’s-complement signed integer representation, but signed overflow is still undefined. Out-of-range integer-to-signed conversion remains implementation-defined or can raise an implementation-defined signal. _BitInt has additional promotion rules beyond this guide.

Check the source rules

Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.

Say it in your own words

Why is casting the completed integer quotient to double too late to produce 2.5?

Compare with an explanation

The integer division already produced 2. A later conversion preserves that value; it does not repeat division with floating operands.

Read this guide in its chapter
05Function callsA call passes values into a separate executionFollow the argument, its parameter, and the object a pointer can still reach.

A call passes values into a separate execution

For a function with a suitable prototype, argument values are converted to the parameter types. Each parameter is a separate object for that call. A copied pointer value can still designate an object in the caller.

When this helps Use this model to understand output parameters, independent recursive calls, and the difference between changing a parameter and changing its target.

Read the ideas side by side

Argument
The expression supplied at the call, such as score or &score.
Parameter
The named object used by that call’s function body, such as value or target.

A parameter is not a second name automatically bound to the caller’s variable.

Change a copied int
value = 9 changes the parameter object value.
Write through a copied pointer
*target = 9 changes the live int object designated by the copied pointer.

C still passes a value in both calls.

Function declaration
Introduces the function and, with a prototype, describes its parameter types.
Function definition
Also supplies the body executed when that function is called.

A body must be provided where required; a declaration alone does not supply the implementation.

Follow the reasoning

The pointer call below receives &score, so its target is a valid live int. The function is not a general validator for arbitrary pointers.

C17 · illustrative fragments in the stated context

  1. void change_copy(int value) { value = 9; (void)value; }
  2. void change_target(int *target) { *target = 9; }
  3. /* inside a caller: */
  4. int score = 4;
  5. change_copy(score);
  6. change_target(&score);
  1. Initialize the caller’s object

    score is an int object holding 4.

  2. Call change_copy

    The value 4 is passed to its int parameter. Assigning 9 to that separate parameter does not assign to score.

  3. Return from the first call

    The parameter’s lifetime ends. score still holds 4.

  4. Call change_target

    &score supplies a pointer value. The parameter target receives that value and designates score.

  5. Write through target

    *target = 9 changes score. Returning ends the pointer parameter’s lifetime, not the caller’s score object.

Common misconceptions

These statements are misleading. Open each one to see why.

MisconceptionPassing a pointer switches C into pass-by-reference.

The pointer value is passed by value. It permits indirect access to a suitable target, while the parameter remains a separate pointer object.

MisconceptionA recursive call overwrites the previous call’s parameters.

Each active call has its own automatic parameter objects. A shared static object, if used, is a separate issue.

MisconceptionFunction arguments are always evaluated left to right.

C does not generally specify their evaluation order. Avoid depending on an order, especially when arguments read and modify the same object.

Go a little deeperOptional technical detail

Array parameter spelling does not copy an array

A parameter declared as an array is adjusted to a pointer parameter. Pass the needed count separately or use an interface with a clearly documented size contract.

Macros do something different

A function-like macro substitutes preprocessing tokens. It does not create parameter objects or a function call boundary. Parentheses can fix grouping while leaving repeated evaluation possible.

C17 In C17, a declaration such as int f(); does not provide a parameter-type prototype. int f(void); explicitly declares no parameters. The guide’s calls use prototypes.

C23 In C23, an empty parameter list in int f(); specifies no parameters and provides a prototype. This change does not make function arguments evaluate left to right.

Check the source rules

Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.

Say it in your own words

If target is a copy, how can *target change score?

Compare with an explanation

The copied pointer value still designates score. Changing target itself and writing through *target are different operations.

Read this guide in its chapter
06Undefined behaviorA valid explanation starts with a valid operationSeparate a language guarantee, a documented choice, and an operation C does not define.

A valid explanation starts with a valid operation

Undefined behavior means the C standard imposes no requirements for that situation. It is not a request to guess a surprising output. First ask whether each evaluated operation satisfies its contract.

When this helps Use this habit before tracing bounds, expired objects, arithmetic limits, and expressions with interacting side effects.

Read the ideas side by side

Unspecified behavior
The standard permits alternatives without requiring the implementation to document which one is chosen.
Implementation-defined behavior
A permitted choice must be documented by the implementation.

Both have language-defined boundaries; neither is a synonym for every possible outcome.

Undefined behavior
The standard imposes no requirements for the affected situation.
Constraint violation
A translation unit violates a constraint. A conforming implementation must issue at least one diagnostic for that unit.

A diagnostic is not necessarily a refusal to compile; not every undefined operation requires a diagnostic.

A successful observed run
Describes one run with one build and environment.
A language guarantee
Applies under the stated C rules and preconditions.

An observation alone does not prove that the program has defined behavior.

Follow the reasoning

Do the bounds check before any subscripted read. This example deliberately chooses the one-past index and takes a safe alternative.

C17 · illustrative fragments in the stated context

  1. int values[3] = {3, 6, 9};
  2. size_t index = 3;
  3. if (index < 3) {
  4. /* values[index] may be read here */
  5. } else {
  6. /* handle the missing element */
  7. }
  1. Establish the valid indexes

    The three-element array has indexes 0, 1, and 2.

  2. Read index as a value

    index holds 3. Holding that integer value is not itself an invalid array access.

  3. Evaluate the guard

    index < 3 is false. No array subscript has been evaluated to read an element yet.

  4. Skip the element access

    The guarded branch is not executed. The program does not read values[3].

  5. Handle the missing element

    The else branch reports no element. It supplies defined behavior for this case instead of relying on an out-of-range read.

Common misconceptions

These statements are misleading. Open each one to see why.

MisconceptionUndefined behavior means the program must crash at that line.

The standard promises no specific symptom or point of failure. A build can appear to work, fail, or behave differently after optimization.

MisconceptionTwo’s complement guarantees signed wraparound.

A representation rule does not define overflowing signed arithmetic. Check before computing when a signed result might exceed its type’s range.

MisconceptionA sanitizer proves the whole program has no undefined behavior.

A sanitizer checks supported conditions on executed paths. Tests and diagnostics help, but they do not cover every path or every language rule.

Go a little deeperOptional technical detail

Precedence does not establish evaluation order

Parentheses group an expression. They do not generally sequence its operands. Analyze i++ + i++ as an unsequenced side-effect conflict; do not run it to discover a portable answer.

Prevent the invalid operation, not just the visible result

A guard must be evaluated before the dangerous access or arithmetic. Reading values[index] first and checking index afterwards has already crossed the boundary.

C17 These bounds and sequencing rules apply to the C17 baseline. Keep the distinction between runtime undefined behavior and translation-time constraint diagnostics.

C23 C23 does not make out-of-bounds reads, accesses to expired objects, or unsequenced modifications safe. Two’s-complement representation still does not define signed arithmetic overflow.

Check the source rules

Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.

Say it in your own words

Is merely storing index = 3 undefined for this three-element array?

Compare with an explanation

No. The integer value can be stored and tested. The guarded example avoids the invalid element access, so it can safely handle that value.

Read this guide in its chapter
Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping