- [Instructor] Variables are strongly typed
in both C++ and C,
and that means that the token representing the variable
represents both its value and its type.
So here's a working copy of working dot CPP
from chapter two of the exercise files.
I'm going to come down here and I'm just going to
declare a variable.
Int I, like this.
So this is actually a variable definition
as well as a declaration.
Definition means it allocates space,
so, technically speaking, this line of code,
this expression here, int I,
this defines the name and the type of the variable
and it allocates space of a size sufficient
to hold a value of that type.
So, this variable is an integer.
Currently, it has no assigned value,
so it's said to be undefined.
An undefined value is a very dangerous thing,
so always be sure to assign a value to a variable
before you use it.
So I'm going to come down here and say
I equals seven.
Now that variable has a value,
it's no longer undefined.
So always be sure to assign a value to a variable
before you use it.
So, once you've defined the variable,
you can assign a value to it
and this is called initializing the variable.
So, this variable is now declared, defined and initialized.
And I can come down here
and I can print its value using printf.
And I'll just delete that extra hello world there.
And now I can build and run,
and you see the result is the value is seven.
So this expression here, just the I by itself,
reads the value of the variable
and it passes it on to the printout function.
Now under many circumstances,
you may both define and initialize a variable
at the same time like this.
And now all in one statement,
I've both defined and initialized the variable.
It's usually a good idea to initialize a variable
as soon as possible,
so I'll usually initialize it when it's defined,
just like this.
And of course, when I build and run,
we get exactly the same result.
C++ also uses qualifiers, sometimes called modifiers,
that change the behavior of variables in various ways.
The qualifier becomes part of the type.
And so I can say const, int, I equals seven.
And const is a very common qualifier, you'll see it a lot,
it's short for constant
and it tells the compiler that the value of this variable
cannot change once it's defined.
This is also called a read-only or immutable variable.
Now if we try to change it,
the compiler will complain about it,
it'll throw an error if I say I equals 42 like this.
Notice that I immediately get this cannot assign
to variable I with const-qualified type const-int.
So it's calling this a const-qualified type
because I've used the qualifier const.
And that means that I can't change its value,
so if I try to build here it says build failed
and it tells me why.
So if I delete that, again,
we're back in business and it works.
So in both C++ and C,
the variable must be defined before it can be used,
the fundamental types and qualifiers
are covered in more detail in the datatypes chapter.