MESSAGE
DATE | 2010-03-21 |
FROM | Ruben Safir
|
SUBJECT | Re: [NYLXS - HANGOUT] C++ Workshop - Syntax Basics -- functions
|
Function Arguments:
We have already noted that the general rule for the input of functions is the argument, or parameter list within the call operator. furthermore, the default rule is that data in variables is copied into the function body, creating a new set of data that is local to the scope of the function. And we also stated that there is important exceptions to this rule.
If you want to affect data that exists outside of your function, there are several important methods to do so. The most basic method is the use of pointers. When a pointer is defined in a scope global to the your function, and when there is a value attached, memory is allocated outside your function for the data and that can be manipulated within the scope of your function. Data that is created within your function, even if assigned to a pointer, still remains within your function only, and disappears when the return value is only the pointer and when your function instance ends. Let us look at this behavior.
_______________________________________________________________________
#include using namespace std;
int global_a, * ptr_a; int scope_data(int); int * scope_pointer(int *);
int scope_data(int in){ in = 1000; int out = 25; return out; }
int * scope_pointer(int *in){ *in = 1000; int * out; int buf = 25; out = &buf; cout << "The value of 'out' within function scope_pointer ==> " << *out << endl; return out; }
int main(int argc, char * argv[]){
int func_return, *func_ptr_return; global_a = 5; ptr_a = &global_a;
func_return = scope_data(global_a); cout << "global_a ==>" << global_a << endl; cout << "ptr_a value==>" << *ptr_a << endl; cout << "function return ==>" << func_return << endl;
func_ptr_return = scope_pointer(ptr_a); cout << "\n\nPointer Behavior\n"; cout << "ptr_a value: Since ptr_a points to global_a, the memory \ \nsegment is retained with the new value ==> " << *ptr_a << endl; cout << "\n\nFunction ptr return value:meaningless garbage \ \nsince buf is out of scope ==> " << *func_ptr_return << endl <
return 0; }
_____________________________________________________________________________
ruben-at-www2:~/cplus/functions> g++ -Wall function_scope.cpp -o scope.bin ruben-at-www2:~/cplus/functions> ./scope.bin global_a ==>5 ptr_a value==>5 function return ==>25 The value of 'out' within function scope_pointer ==> 25
Pointer Behavior ptr_a value: Since ptr_a points to global_a, the memory segment is retained with the new value ==> 1000
Function ptr return value:meaningless garbage since buf is out of scope ==> 108
|
|