This is a very nice introduction for the
"pass by value vs. pass by pointer"
It shows good examples, and pointed out the difference
-1- between C and C++
-2 Common variables and arrays
-1- between C and C++
In C, if we want to pass by pointer: we need to :
void squareIt(int *toBeSquared);
Then in the main-function:
#include <stdio.h>
void squareIt(int *toBeSquared);
int main(void)
{
int valueToSquare = 5;
/* Because we're changing the value of the variable in the
function, we need to print its initial value before we call
the function */
printf("%d squared is ", valueToSquare);
/* Pass the address of the variable to the function.
Note we have no = in this function call; the function
does not return anything directly to the caller, so there's
no need; in fact, it should cause a compilation error. */
squareIt(&valueToSquare);
/* And print the result */
printf("%d\n", squaredValue);
return 0;
}
void squareIt(int *toBeSquared)
{
/* Operate directly on the passed-in value, which
means there's nothing to explcitly return. */
*toBeSquared = (*toBeSquared) * (*toBeSquared);
}
---> however, C++ Pass-By-Reference
Now C++ -- not C -- has a nifty little feature called pass-by-reference, which hides that icky pointer notation from you,
making your code somewhat easier to read. To use this in C++, you will use that same & operator, only this time it's part of the arguments in the function signature, rather than on the argument provided by the caller.
So now we can use:
void squareIt(int &toBeSquared); \\ note that this is in the definition of the function and in main we change to use:
#include <iostream> // Pass the variable by reference
void squareIt(int &toBeSquared);
int main()
{
int valueToSquare = 5;
std::cout << valueToSquare << " squared is ";
// Note, we pass the variable AS IS, no & necessary!
squareIt(valueToSquare);
std::cout << valueToSquare << std::endl;
}
void squareIt(int &toBeSquared)
{
// Here we get rid of the icky pointer notation
// Note that using *= is the same as the above
// toBeSquared = toBeSquared * toBeSquared;
toBeSquared *= toBeSquared;
}
-2 Common variables and arrays
a) arrays are automatically passed by pointer.
b) we have passed a second variable, size. This is required when passing arrays because the array is being treated as a pointer within the function. If we're going to operate on the array within the function, we need to know the bounds of the array, else we're going to go off into memory we don't own and cause the program to crash.
--
♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥
No comments:
Post a Comment