FEE 132 Computer Labs
FEE 132 Computer Labs
int main(void)
{
int x = 1; int y = 2;
int tmp = x;
x = y;
y = tmp;
int main(void)
{
int x = 1; int y = 2;
mySwap(x, y);
• Pointer
• contains an address of a variable that contains a specific value
• A pointer indirectly references a value
• Referencing a value through a pointer is called indirection
Pointers
Pointers
• Pointers, like all variables, must be defined before they can be used
int y = 5;
int *yPtr;
yPtr = &y;
Pointers
Pointers
• The unary * operator, commonly referred to as the indirection
operator or dereferencing operator, returns the value of the object
to which its operand (i.e., a pointer) points
int* c = &a;
int* d = &b;
int e = a + b;
int f = (*c) + (*d);
What is the final value of a, b, c, d?
int a = 10;
int b = 30;
int* c = &a;
int* d = &b;
mySwap(&x, &y);
This gets the address of x and y and supplies those as inputs to the
function mySwap
Passing Arguments by Reference Vs Passing by
Value
int a = 10; int b = 30;
Vs
int main(void)
{
char * s = “hello”;
char * t = “hello”;
// try (and fail) to compare strings NB: Comparing strings in this way
if (s == t) doesn’t work! Try it out!
{
cout << "You typed the same thing!\n";
}
else
{
cout << "You typed different things!\n";
}
}
#include <iostream>
#include<string>
int main(void)
{
string s = “hello”;
string t = “hello”;