Professional Documents
Culture Documents
CS 111 Computing Fundamentals: Functions (2) Dr. Christina Class
CS 111 Computing Fundamentals: Functions (2) Dr. Christina Class
CS 111 Computing Fundamentals: Functions (2) Dr. Christina Class
Fundamentals
Functions (2)
Dr. Christina Class
Repetition
Functions: Variables
Local variables
Variables that are defined within a function
a local variables
They are administered automatically by the
runtime system.
Their initial value is undefined.
They can only be accessed from within the
function that defined it.
They will be removed from the memory
when the function ends.
Remark for SIC students: They are stored on
the stack.
CS 116 – Summer 2014/15 - Dr. Christina Class - Lecture 11 4
Sharing of information between a
function A and the function B that
called the function A:
from the caller to the function: using
parameters
from the function to the caller: using
the (only one) return value
Functions can also share
information by using global
variables.
CS 116 – Summer 2014/15 - Dr. Christina Class - Lecture 11 5
Global variables
int a;
global variable
void read(void)
{
scanf("%d",&a);
}
void write(void)
{
printf("a = %d\n", a);
}
int main()
{
read();
write();
return 0;
}
int a;
void read()
{
scanf("%d",&a);
}
void write()
{
printf("a = %d\n", a);
}
int main()
{
write();
read();
write();
return 0;
}
void myFunction(void)
{
int value=1;
printf("The value is: %d.\n", value);
value++;
}
int main()
{
myFunction();
myFunction();
myFunction();
return 0;
}
CS 116 – Summer 2014/15 - Dr. Christina Class - Lecture 11 12
static variables
void myFunction(void)
{
static int value=1;
printf("The value is: %d.\n", value);
value++;
}
int main()
{
myFunction();
myFunction();
myFunction();
return 0;
}
CS 116 – Summer 2014/15 - Dr. Christina Class - Lecture 11 14
Variables
int main()
{
int a = 15;
toSquare(a);
printf("a in main: %d\n",a);
return 0;
}
CS 116 – Summer 2014/15 - Dr. Christina Class - Lecture 11 18
If we wish to change the value in
the calling code segment, we need
to use a return value and assign it
to the variable.
int toSquare(int a)
{
a = a*a;
printf("a in toSquare: %d\n",a);
return a;
}
int main()
{
int a = 15;
a = toSquare(a);
printf("a in main: %d\n",a);
return 0;
}
CS 116 – Summer 2014/15 - Dr. Christina Class - Lecture 11 20
Arrays as parameters
Arrays can be used as parameters but not
returned by a function.
Arrays are call-by-reference
parameters, i.e. the function and the
caller share the same array copy and all
changes are permanent.
The length in the parameter definition of
an array is ignored.
When the function is called, only the
name of the array is passed as parameter.