ConceptStep · learning platform for computer science

Scope and local variables

C programming · Lesson

C · lesson 14 / 27

Scope and local variables

Compare two variables with the same name that belong to different frames.

1 · Observe and predict

The concept

incrementa's parameter x is distinct from main's x: changing the local copy does not automatically change the caller's variable.

Mental model:

main x=5 → incrementa x=5 → local x=6 → return 6 → main x stays 5

2 · Algorithm view

Observe the equivalent algorithm

For functions the flowchart shows the algorithmic effect. The Call Stack Explorer below shows what really happens between main, parameters, frames and return.

Loading flowchart…
3 · Call Stack Explorer

Follow the call frame by frame

Move through the steps: frames show which variables exist at that moment and the source highlights the involved lines.

1 / 4

main creates its own x

This x belongs to main's scope.

main
x5
4 · Flowchart ↔ C · Run in Page

Lab 1 — Run the example program

Run C executes only the example shown on the left, using stdin on the right. The coding challenge below has a separate editor and test button.

Scope and local variables Start the flowchart to synchronize the code
                        1#include <stdio.h>
                        2 
                        3int incrementa(int x)
                        4{
                        5    x = x + 1;
                        6    return x;
                        7}
                        8 
                        9int main(void)
                        10{
                        11    int x = 5;
                        12    int y = incrementa(x);
                        13    printf("%d\n", x);
                        14    printf("%d\n", y);
                        15    return 0;
                        16}
Ready. Make a prediction before running.

                    
                

Lab 2 — Coding challenge: write your code — Pass-by-value parameters

Write incrementa(int x) returning x+1. Read x, call it and print the returned value then the unchanged x.

This is a different program from lab 1. Complete the starter code: Check all test cases compiles this editor and tests every input, including boundary cases.

5 · Guided practice

Check your prediction

After y = incrementa(x), what is main's x?

Challenge 1 / 5 · Understanding

Progress: 0 / 5 · correct: 0

Your competency map

What you need to know for Scope and local variables

ConceptStep separates what is required from what is recommended or useful as reinforcement. Only required prerequisites block your progress.

Current topic Strong skill Review due Needs reinforcement To be mastered Optional support

Relationships: solid line = required · dashed line = recommended · dotted line = reinforcement.

GUIDED LEARNING PATHS

Want to choose the next skill to develop?