Saturday, July 17, 2010

C++: Variable basics: declaration and assignment

So, let's talk about how to even declare data or variables and how to assign
some value to it.

To declare a variable, we need three information: the type of the variable,
the actual name of the variable and what values will it assign to. First,
declare the type of a variable e.g. int, char, etc., followed by the name of
the variable. For instance, if we are to create an age difference calculator
program (perhaps to find out who is older), we would say;
int user_age;
Here, we have declared an integer variable called "user_age," which
(hopefully) would be useful for storing our age (in my case, I'm twenty).
After this, we can use a number of ways to assign this variable to a value:
using the next statement and writing the assignment statement, or using the
"assignment operator" (=) to write our assignment. Note that this assignment
operator is way different from the way we use equals for other tasks and is
read differently. (I'll talk about different operators in C++ later.) For
example:
int my_age = 20;
and
int my_age; my_age = 20;
are both valid. In both scenarios, the code is read as, "20 is assigned to
my-age" or "my_age is assigned 20." Also, you can do this:
int my_age (20);
which is also valid (especially in this case).

The other variable types follow almost the same format as the integer
example above. For our string variable (you need to include the string
library), we could use:
Sstring s = "whatever";
Or
Sstring s1; s1 = "whatever";
And both of them are perfectly fine. Note that when you do assign a string
to the string variable, be sure to enclose the actual string it within
quotes.

Few more examples:
Suppose if we want to declare a decimal value for calculating a car's
mileage. We can write:
Ffloat mpg;
or
double mpg;
Of these two values, the "double" type would have greater accuracy.

Now suppose if you are asked to write a voter registration program which
asks user if they are above eighteen or not. We can say:
Bool above_age;
Now we have created a Boolean variable which tests if the age entered by the
user is greater than 18 or not. I'll come back to this small code later when
I discuss conditional statement.

Next: useful operators...

No comments:

Post a Comment