For this experiment, we will do some more things with the integer declarations in the original program.
The integer data type in C++ is denoted with the int
keyword. This is the type most commonly used in the declaration of integer
variables and constants. Other integer types include short int
,
long int
, unsigned
, and some others.
From the first experiment, you know that you can change the initial
values of count
and number
by changing the initialization
expressions. What happens though, if an initialization expression is
not an integer?
Change the initialization expression of count
to be a literal
string instead of an integer. A string begins and ends with double
quotes:
"this is a string"
Compile the program.
Question #2.2.1: What, if any, is the first error message that the compiler gives you?
It seems that the compiler will save you from making an initialization mistake. The problem here is that a string of characters cannot be turned into an integer very easily. But what if the data types were very similar and could be converted easily?
Nowchange the initialization expression of count
to be a
literal character — that is, a single character enclosed in single
quotes; for example, 'f'
.
Compile the program.
Question #2.2.2: What, if any, is the first error message that the compiler gives you?
You might be surprised at this point that your compiler
didn't give you an error message. Most will not. The
int
and char
data types in C++ are very closely
related, and you probably won't get an error for initializing an
int
with a char
. This is because a single
character is represented in the computer's memory as an integer.
So it's very easy for the compiler to switch between the two.
Some compilers may issue a warning for this initialization since
often this is a programming mistake; either count
should be
declared as a char
, or the initialization is wrong. As with
all compiler error messages, you should watch out for such warnings.
What about a real number, something with a decimal point in it?
Change the initialization of count
to be 3.14159
and compile the program.
Question #2.2.3: What is the first error message or warning that the compiler gives you?
Again, you probably don't get a error message, but you might have gotten a warning.
Finally, let's try something quite off-the-wall and initialize
count
to be equal to cin
. This seems like a
ridiculous thing to do, but go ahead and see what the compiler does.
Compile the program.
Question #2.2.4: What is the first error message or warning that the compiler gives you?
This time you should get an actual error message.
Before continuing to the next experiment, reset count
so
that it is initialized to a proper integer.