C5: Functions Flashcards
What is a function in C?
A function in C: a series of statements that has
been grouped (in a block) and given a name. Functions are the main building blocks of C
programs
• They modularize a program, making it easier to read
• They avoid code duplication and allow code reuse
What is a function prototype?
It is a declaration of a function before it is defined so that it can be used before it’s defined. (“Only needed if function definition after function call”)
What is: double max(double, double);
function prototype
What is “call by value”?
When a function gets its own copy of arguments (passed in as parameter list). The function ONLY gets a copy of the original values, not the actual data. changes to copy do not change original.
What is “call by reference”?
Function can directly access data and changes affect original. In C, the pointer is copied (i.e. the value of the pointer).
Note: there is no actual call by
reference in C
§ We just simulate it with pointers
Give an example of simulating calling by reference in C.
Example of passing by reference by copying address of a variable and passing address to function, which creates a pointer that holds the same address (points to the address):
void myFunction(int * data){ *data = 10;} //... int main(void){ int x =5; myFunction(&x); //now x = 10 }
What is an activation record?
An activation record is the portion of the stack used for an invocation of a function and is also called stack frame.
What is a stack?
Calls to a function requires its own instantiation of local variables. Functions can only return when all functions it has called are returned following LIFO principle. This structure is a LIFO structure and is called the stack and it holds each (function) instantiation.
Is it ok to return an array instantiated in block scope?
No, if you need to return an array:
–create a struct with an array attribute and return the struct
bad: char * getMessage (void) { char aMessage[] = “hello world”; char *result = &(aMessage[0]); return result; }
Is it ok to return a pointer pointing to a variable in block scope?
No,
if you need to return a pointer in general:
–instantiate the pointer on the heap and not in the function’s stack (char * result; result = malloc(6); … return result;)
OR
–instantiate the pointer on the caller’s stack and pass by [simulated] reference (char str[6];
getMessage(&str); )
What is a static function?
It is a function declared with the keyword static. It is only locally visible within the file defining it. (It uses internal linkage.)