Professional Documents
Culture Documents
FUNCTION
FUNCTION
int main() {
string food = "Pizza";
string &meal = food;
C++ Pointers
cout << food << "\n";
cout << meal << "\n"; Creating Pointers. You learned from the
return 0; previous chapter, that we can get
} the memory address of a variable by
using the & operator:
Memory Address
#include <iostream>
In the example from the previous page, #include <string>
the & operator was used to create a using namespace std;
reference variable. But it can also be used to
get the memory address of a variable; which int main() {
is the location of where the variable is stored string food = "Pizza";
on the computer.
cout << food << "\n";
When a variable is created in C++, a memory
cout << &food << "\n";
address is assigned to the variable. And when
return 0;
we assign a value to the variable, it is stored
}
in this memory address.
1
A pointer variable points to a data Tip: There are three ways to declare
type (like int or string) of the same pointer variables, but the first way is
type, and is created with preferred:
the * operator. The address of the
variable you're working with is
assigned to the pointer:
#include <iostream>
#include <string>
using namespace std; C++ Dereference
2
When used in declaration C++ Functions
(string* ptr), it creates
a pointer variable. A function is a block of code which only runs
When not used in declaration, when it is called.
it act as a dereference
operator. You can pass data, known as parameters, into
a function.
C++ Modify Pointers
Functions are used to perform certain actions,
and they are important for reusing code:
Modify the Pointer Value. You can
also change the pointer's value. But Define the code once, and use it many times.
note that this will also change the
value of the original variable: Create a Function:
3
Call a Function: #include <iostream>
using namespace std;
Declared functions are not executed
immediately. They are "saved for later use",
void myFunction() {
and will be executed later, when they are cout << "I just got executed!\n";
called. }
To call a function, write the function's name
followed by two parentheses () and a int main() {
semicolon ; myFunction();
myFunction();
In the following example, myFunction() is myFunction();
used to print a text (the action), when it is return 0;
called: }
Inside main, call myFunction():
Function Declaration and
#include <iostream> Definition:
using namespace std;
A C++ function consist of two parts:
void myFunction() {
cout << "I just got executed!"; Declaration: the return type,
} the name of the function, and
parameters (if any)
Definition: the body of the
int main() {
function (code to be executed)
myFunction();
return 0;
}
4
#include <iostream>
using namespace std;
// Function declaration
void myFunction();
// Function definition
#include <iostream> void myFunction() {
using namespace std; cout << "I just got executed!";
}
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}