const
12/19/2016
Here we will go over the const
keyword.
#include <cstdio> #include <string> using namespace std; int main() { string message = "Message"; message += " for you!"; /* Visual Studio: */ getchar(); return 0; }
Here we declare a string and initialize it with the
value "Message"
. We then
append " for you!"
,
making message
contain "Message for
you!"
. Let's extract out this appendage to a
function.
void append(string& str) { str += " for you!"; } // in main() append(message); // was `message += " for you!";`
When we pass a variable by reference to a function, we are sharing it with the function. When we share it, they are also given write access to the variable. Many times, we wish to share with only read access. Our append function requires write access into the variable because it outputs data into it. Let's make a print function to see why we would want read-only access.
#include <iostream>
void print(string& str) {
cout << str;
}
The str
parameter is taken
by reference. Just like
in append
, we are able to
modify the string
. Since
our print function doesn't actually modify the string, we
should tell the computer that it won't. To do this, we
add the keyword const
before the ampersand marking it as a reference:
void print(string const& str) {
cout << str;
}
Before it was const
,
writing
print("The milk man is
here");
would give us an error at compile time.
Marking it as const
allows it to work. This shows us an important aspect
of const
references: they
allow the code to use temporary variables as arguments.
Since the parameter is taken as
a const
reference, it
also prevents print()
from modifying
the string
. So the
following code would also not compile because it modifies
the parameter that is marked as unchangeable:
void append(string const& str) { str += " for you!"; }
Note that const&
parameters only mean that the access to the variable will
be constant, not that the actual variable
is const
.