CS 450 Notes Chapter 3
- Introduction
- More constants
constant pointers and pointers to constants.
const int* ptr;
ptr is a pointer that points to a const int.
So ptr can be changed, but the thing it points to can't. Oddly,
int const* ptr;
means the same thing.
To get a pointer that can't be changed, do
int * const ptr;
ptr is constant and points to an int.
To combine these
int d=1;
const int * const ptr = &d;
int const * const ptr = &d;
Neither can be changed in this case. Some examples
int d = 1;
const int e = 4;
int *u = &d // ok
int *v = &e // illegal, e const
int *w = (int *)&e; // legal but bad
String constants. From the above
char *ptr="hello,world";
should be illegal since the quoted string is a constant to the compiler.
But much C code does this so it is allowed.
Changes are undefined behavior and a bad idea.
const parameters
Parameters can be declared const.
This should be done on parameters that aren't to change.
The compiler will catch these.
int
nyarf::foo(int s,const int n) {};
Sort of redundant as C++ is pass by value.
Changes to n wouldn't change the actual parameter anyway.
Could be a little confusing to the caller.
It really means you won't change the formal parameter inside the function.
Could do this to make it more explicit.
int
nyarf::foo(int s,int n)
{
const int& local = n;
}
advantage slight, the caller doesn't have to think about it, but you still
get the checking.
const function
Functions can be declared const.
This means that the compiler prevents
that function from changing the class variables.
int
nyarf::foo(int s,int n) const {};
foo would be prevented from changing any of the private variables in the
class nyarf.
This is another way to prevent accidents.
Reference parameters
C++ has added an actual pass by reference ability to parameter passing.
In C, this was simulated by passing pointers to pointers.
For example, to write a function that changes the value of an integer,
you would start with
void
change(int n)
{
n=7;
} /* change */
If used like
int a=9;
change(a);
print a;
a would still be 9 after the call.
This is because C passes a copy of the
value of a to the function.
So we try
void
change(int *n)
{
*n=7;
} /* change */
This will change the value of a as the the parameter is now the address
of the variable which we dereference and thus get the address of the actual
variable we want.
However we have to remember to call it with
change{&a);
A simple call to change(a) would result in our attempting to change whatever
is stored at memory location 9 to 7, probably not what we want.
C++ reference parameters make this more natural.
void
change(int& n)
{
n=7;
} /* change */
Now we can call change(a) and
a will change to 7 as desired.