← C++ from Scratch
Lesson 31 of 62 · 10 XP
Scope
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A variable is visible only in its own { } block and the blocks nested in it:
int total = 0; // global: visible to all the functions below (use rarely)
void f()
{
int x = 1; // local: only inside f
{
int x = 2; // a different x — it "shadows" the outer one inside this block
}
// here x == 1 again
}
- local variables are created on entering a block and disappear on leaving it;
static int calls = 0;inside a function is created once and keeps its value between calls;- global variables make a program more complicated: any function can change them. It's better to pass parameters.
Task. Write a function int nextId() that returns the next number on every call: 1, 2, 3… —
using a static variable inside the function, without globals. Read n and print n numbers separated by spaces.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.