Copies and scope
Read · 1 of 4
Functions work on copies
When you call f(a), the function gets a copy of a's value. Changing it inside the function doesn't touch a in main. (Pointers, in module 9, are how a function changes the caller's variable.)
Variables made inside a function exist only while it runs. Two functions can each have their own i without clashing.
Read this lesson as text
A function gets copies of its arguments, and its variables live only inside it.
Functions work on copies
When you call f(a), the function gets a copy of a's value. Changing it inside the function doesn't touch a in main. (Pointers, in module 9, are how a function changes the caller's variable.)
Variables made inside a function exist only while it runs. Two functions can each have their own i without clashing.
Did it change?
#include <stdio.h>
void addTen(int x) {
x = x + 10;
}
int main() {
int a = 5;
addTen(a);
printf("%d\n", a);
return 0;
}What does this print?
- 5
- 15
- 10
Show the answer
5 addTen changed its own copy. a in main is still 5. To get 15, return the new value and store it: a = addTen(a).
Exercise: Write isPrime()
Write int isPrime(int n) returning 1 for a prime and 0 otherwise (1 and below are not prime).
Read a number k, then print every prime from 2 to k on one line, separated by spaces.
Exercise: Greatest common divisor
Write int gcd(int a, int b) with Euclid's method: while b isn't 0, replace (a, b) with (b, a % b); then a is the answer.
Read two positive numbers and print their gcd.