Function arguments are local to the function call. Reusing a name inside the function does not overwrite the outer value.

Program

Play the script to see outer x stay 5 while the function uses its own x.

scope.R
Replay: real traced execution (multi-file project)
x <- 5
bump <- function(x) { x + 1 }
inside <- bump(10)
label <- paste(x, inside, sep = ":")
cat(label, "\n", sep = "")
  1. x ← 5

    1x <- 52bump <- function(x) { x + 1 }
    values this step5x
  2. bump ← function(x)

    1x <- 52bump <- function(x) { x + 1 }3inside <- bump(10)
    values this stepfunction(x)bump
  3. inside ← 11

    2bump <- function(x) { x + 1 }3inside <- bump(10)4label <- paste(x, inside, sep = ":")
    values this step11inside10argument x
  4. label ← 5:11

    3inside <- bump(10)4label <- paste(x, inside, sep = ":")5cat(label, "\n", sep = "")
    values this step5:11label5x11inside
  5. cat(label, " ", sep = "")

    4label <- paste(x, inside, sep = ":")5cat(label, "\n", sep = "")
    output5:11
    values this step5:11label

Follow the Names

  1. The outer x starts as 5.
  2. bump(10) passes 10 as the function's local argument x.
  3. Inside the call, local x + 1 gives 11.
  4. inside stores 11.
  5. paste(x, inside, sep = ":") uses outer x and inside, giving 5:11. | name | value | where it is used | | --- | --- | --- | | outer x | 5 | final label | | argument x | 10 | inside bump | | inside | 11 | final label | | label | 5:11 | stdout |
scope Scope controls which value a name refers to.
argument The function argument `x` is local to the call.
outer value The outer `x` remains unchanged after `bump(10)`.

Exercise: scope.R

Reproduce the output 5:11, then trace why the outer x stays 5 while bump(10) returns 11.