fork download
  1. #!/usr/bin/env bash
  2. # dynamic_scope_demo.sh
  3. # Mirrors the C-like program from the hand-out under dynamic scoping.
  4.  
  5. ############################
  6. # global variables (start all at 0)
  7. ############################
  8. a=0
  9. b=0
  10. c=0
  11. d=0
  12.  
  13. ############################
  14. # g1, g2, g3
  15. ############################
  16. g1 () { # signature: g1(int b ; int c)
  17. local b=$1 c=$2
  18. printf '%d %d %d %d\n' "$a" "$b" "$c" "${d:-0}"
  19. }
  20.  
  21. g2 () { # signature: g2(int a ; int c)
  22. local a=$1 c=$2
  23. g1 "$a" "$c"
  24. }
  25.  
  26. g3 () { # signature: g3(int c ; int a)
  27. local c=$1 a=$2
  28.  
  29. local b=3
  30. g1 "$a" "$b" # first print-line
  31.  
  32. # -------- inner block --------
  33. local c=8 # shadows the parameter c
  34. local d=4
  35. g2 "$a" "$b" # second print-line
  36. unset d # end of inner block – restore older ‘d’
  37. # -------- end block ---------
  38.  
  39. g1 "$a" "$b" # third print-line
  40. echo "$b" # “return” value
  41. }
  42.  
  43. ############################
  44. # main
  45. ############################
  46. main () {
  47. local a=4
  48. local b=5
  49. a=$(g3 "$b" "$c") # c is still the global 0
  50. g3 "$b" "$a"
  51. }
  52.  
  53. main
  54.  
Success #stdin #stdout #stderr 0.01s 5300KB
stdin
Standard input is empty
stdout
0 0 3 0
0 0 3 4
0 0 3 0
3
stderr
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number