Lecture 2 Flashcards
User Defined Functions, Stack Frames, C Struct, and More I/O
basic function syntax
return_type function_name (argument list) {
//body of function
return statement;
}
ex) int add (int a, int b) {
return a + b;
}
basic function with no return syntax
void function_name (argument list) {
//body of function
}
*no return statement because return_type is void
function prototype syntax
return_type function_name (arg list);
ex) int add(int a, int b);
what is a function prototype?
definition of the function without initializing it
can you call a function prototype in main( ) and then initialize it after main( )?
yes, you can
the function prototype defines the function (no implementation yet) but the system recognizes it from the prototype
after running through main( ), the system is able to execute the function call since the implementation happens after main( )
can you call a function in main( ) and then define/implement it after main()?
no, the system will stop at the function call because it wont recognize the function call (not defined before called) and wont know what to do for it (not implemented before or after call)
what is the most basic linear data structure in c?
c structures (aka structs)
struct basic syntax
struct name {
field 1;
field 2;
field 3;
};
ex) struct student {
unsigned int pid;
char name[50];
}
can you initialize the fields when you define the struct?
NO, cannot initialize fields within the definition of the struct (syntax)
how do you assign values to the fields of your struct?
using the “.” operator (dot)
ex) student.pid = 12;
*the dot operator goes to that field in memory and assigns the int pid to 12
can you use the dot operator for strings/chars?
NOOO
how do you assign values to string/char fields of your struct?
strcpy( struct.field, “string”);
string function, copies the string then puts into the character array at the allocated indexes for that field
what is the stack frame’s lifetime?
1) created when the function is called
- stores variables local to that
function in the stack frame
- push functions onto stack
2) destroyed when the function returns
- all local variables go out of scope
- pop functions off of the stack
what are the stack’s operations to add/remove functions in the stack?
push –> pushes functions onto the stack when called
pop –> “pops” functions off the stack after they return
what sequence does the stack adhere to?
LIFO (last in first out)