Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

scope and lifetime — concept C23

Scope controls name visibility while lifetime controls object existence; a pointer may remain in scope after its object expires, but dereferencing it is undefined.

Version: C23

Syntax

scope and lifetime

Scope controls name visibility while lifetime controls object existence; a pointer may remain in scope after its object expires, but dereferencing it is undefined.

Declare a variable in the narrowest block that needs it, and never return the address of a local automatic object. A function-local static retains its value between calls, useful for a counter but also shared state requiring synchronization.

A pointer to an array element expires with the array, and reallocation can end an old address’s validity even while the logical collection continues. Also review VLAs, temporary compound literals, and goto paths that may bypass initialization or cleanup.

Examples

#include <stdio.h>

static int next_id(void) { static int id = 0; return ++id; }
int main(void) { int first = next_id(); int second = next_id(); printf("%d %d\n", first, second); return 0; }

Result

1 2

Scope controls name visibility while lifetime controls object existence; a pointer may remain in scope after its object expires, but dereferencing it is undefined.

Sources