Back to Bluesfear
Digital Art



C++ - The Basics Part II
Written by Gary Texmo

iv. variables and data types

 

Variables in C++ are moderately simple and unlike C, they can be declared anywhere within your program. I still like to declare them at the top of my program though with the exception of random counter variables and temporary variables I might need throughout. Anyways, the basic format to declare a variable in C++ is this.

 

<type> <variable name> ( = <value>)

 

Some C++ comilers will initialize your variable to 0 or null, but most don't so it's usually a good idea to initialize it yourself. Anyways, the type is an identifier that tells the C++ compiler what kind of data to set aside for this variable. If you want to really analize it, when it creates an integer it sets aside 4 bytes (or 2 depending on the compiler) of memory, 1 byte for a character, and I think it's something like 8 bytes for a double but I'm not sure. To get by in C++ there are only a few basic data types that you need. Once you understand the concept of them the rest are all the same and a full listing can be found on the internet somewhere :)

 

The data types we will be dealing with are:

·                     int - integer

·                     char - character

·                     char * - string (discuss later)

·                     double - double floating point decimal

·                     bool - boolean

 

Note that some compilers don't allow the use of the bool data type. I'm not sure if it's ANSI C or not but it's very useful and sometimes only requres that you include a file. All Microsoft compilers support the use of the bool data type so I will refer to it. Note that it is quite simple to make your own which I will discuss in a little while.

 

So, say we want to create an integer. We would go,

 

int x;

 

Now we have a variable x which has it's own memory space on the stack. This varible will stay with us throughout it's entire lifetime (discussed in the next section). As I said, depending on your compiler you may not have to initialize the variable with a value, but in most compilers your new variable will contain garbage. Garbage is whatever was left over in that memory space the last time it was used. Don't worry, you won't overwrite anything important (unless you are fooling around with dynamic memory... later). If you don't initialize the variable it sometimes will not work or crash your program so as rule, always initialize your variables to something. So, to ensure that our variable x doesn't hold any garbage, lets initialize it on creation instead.

 

int x = 0;

 

Now when you create x, it automatically takes on the value of 0. Note that this can be any integer number. I hope you know what an integer is... if you don't, go find out right now!!!! :) So anyways... now that we have a variable x, we can use it in any way that we like. Say we want to change the value of x, we could go...

 

x = 8;

 

Now x has the value of 8. The correct terminology is that we have "assigned x the value of 8" because when "=" is used in this form, we call it the assignment operator. When used above we call it the initialization operator. Yea... something a bunch of nerds came up with while sitting around a table playing magic one night I bet. Either way, that's what it's called and that's how you use it. Now that you know that, promptly forget it because nobody really cares. Now, variables can take on any name you like but it must start with a letter or an underscore, and contain only letters, numbers, and underscores as it's name. Also, they can't take the name of any reserved words, such as type identifiers (like int). Also, you can't have varibles of the same name within the same scope (see below). Try to guess which variable declarations are valid and which are not.

 

1) int x = 4;

2) int 4x = 16;

3) bool @myBool;

4) bool myBool;

5) char char = 'B';

6) char _char = 'B';

7) double my-num = 4;

8) double my_num = 4;

9) int iAmNot4giving = 1231;

 

(1) valid

(2) not valid (doesn't start with a letter or an underscore

(3) not valid for the same as (2)

(4) valid

(5) not valid because char is a reserved word

(6) valid because _char is not the same as char

(7) not valid because there is a dash within the variable name

(8) valid

(9) valid

 

If you wish to declare a variable as constant (unchangable) put the const keyword in front of your variable declaration. This is a good idea when you want to ensure that you will not change something, even accidently. Also, you can declare global constants by using the #define keyword at the top of your program beneath the #include lines. When defining these constants you must initialize them with a value but the = sign is not needed. Also, these lines do not have semi-colons after them because they are in fact pre-processor directives, which means when your program is compiled, it finds all occurences of the constant in your code and replaces them with the number. It is an accepted rule to keep all your constants as upper case and your normal variables as mostly lower case.

 

#define PI 3.141592564

 

Lastly, all the usual arithmetic operators apply exept for "to the power of". Some programming languages use ^ to signify "to the power of". In C++ we must use the pow function located in math.h.

 

Example, result = x ^ y would be result = pow(x, y)

 

Now, when you deal with variables, you want to ensure that you are dealing with compatible types. For example

 

double x = 4.5;

int y = x; // yes variables can be initialized with other variables

 

would not produce proper results. Depending on the compiler used, you might get an error, you might get a warning, y might hold 4, or y might hold 5. In this case you would want to use type casting to ensure that your data is converted properly. Therefore we would do this...

 

double x = 4.5;

int y = (int)x;

 

By putting the type in brackets before the variable we cast it to the type we want. This is only advisable with simple data types as it will most likely truncate or modify your data in some way. This can be bad when you are dealing with pointers or other data types. In the case of the pow() function above though, pow() returns data in the form of a double so if you want to get it back as an integer you must cast it. Trigonometric functions are also located in math.h.

 

result = (int)pow(x, y)

 

Here is some example code using variables, also, you can see how we use the io mentioned in the last section to display the results to the screen.

 

// A simple demonstration of variable usage

#include <iostream.h>

#include <math.h>

 

#define PI 3.14159

#define NAME "bob"

 

int main(void) {

      const int hey = 3;

      int x = 0;

      char myChar = 'A';

      char myChar2 = 67;

      double blargh44 = 5.3243;

      int a = 2;

      int b = 3;

      int result = 0;

     

      cout << PI << endl;

      cout << NAME << endl;

      cout << hey << endl << endl;

      // hey = 4 // this would generate an error because hey is a       // constant

      // PI = 4.1 // this would also cause an error

     

      cout << "The value of x after initialization: " << x << endl;

      x = 42;

      cout << "The value of x after assignment: " << x << endl << endl;

 

      cout << myChar << endl;

      cout << myChar2 << endl << endl;

 

      cout << blargh44 << "\t" << blargh44 / 2 << endl;

      blargh44 = blargh44 + 4;

      cout << blargh44 << endl << endl;

 

      result = (int)pow(a, b);

      cout << a << " to the power of " << b << " is: " << result;

      cout << endl << endl;

     

      cout << b << endl;

      b += 3;

      cout << b << endl;

      b--;

      cout << b << endl;

 

      return 0;

}

 

output

------

3.14159

bob

3

 

The value of x after initialization: 0

The value of x after assignment: 42

 

A

C

 

5.3243  2.66215

9.3243

 

2 to the power of 3 is: 8

 

3

6

5

 

Lastly, note the b += 3 line. This is the exact same as saying b = b + 3 but it's just less type. This works with any arithmetical operator such as +, -, *, and /. Also, this is the same with b--. This is the same as saying b = b - 1. -- will decriment your variable by one, ++ will increment it by one. There are two ways to use ++ and --. Either before the variable, or afterwards.

 

x++;

++x;

 

The compiler will first use x, then increment it. This is fine by itself but if used within a logic block it makes a difference. For the second line, the compiler will increment x then use it.

 

So for example (the logic and such will make sense later if it doesn't already).

 

int x = 4;

cout << x << endl;

if (x++ == 4) cout << "TRUE" << endl;

else cout << "FALSE" << endl;

 

x = 4;

if (++x == 4) cout << "TRUE" << endl;

else cout << "FALSE" << endl;

cout << x << endl;

 

output

------

4

TRUE

FALSE

5

 

See how putting the ++ before or after the variable makes a difference? It's important to know so you aren't tearing your head off later on... trust me, that happens and when you realize how stupid a mistake it was you just wanna go fall over in a gutter somewhere.

 

One last thing tonote is that in the interest of readability and style, make your variable names as descriptive as possible. There's nothing wrong with a variable name that takes up half the screen other than that it's fucking annoying. Also, develop your own particular style of capitalization and formatting. I personally format my variable names as lower case first word and then capitolize each word afterwards. For example, int thisIsMyInteger = x; would be my format. I think that's generally used for classes but I did a lot of work with Java (thus writing a lot of classes) for a course once and it stuck. Others like to use underscores to separate words or just capitolize the first letter of each word all the time. Whatever works for you, just try to be consistant. Also, I'm aware of the irony in me stating this because most of my examples in this chapter are using really undescriptive variable names... but that will change when we start talking about more involved topics. So there :)

 

v. data scope

 

In C++ every variable has a lifetime and a scope. The lifetime of a variable is how long it lives. A variable stops "living" when it goes out of scope and is no longer accessable. A variable's scope is the block in which it is contained. In the above example, there is an integer b. It's scope is from the beginning of the main block to the end, signified by the { }'s. You cannot have two variables of the same name with the same scope but, you can have a variable with the same name in a different scope. This is a bit hard to explain and is better demonstrated with an example. Please... consider the following.

 

#include <iostream.h>

 

int main(void) {

      int x = 4;

      cout << x << endl;

      {

            int x = 2;

            cout << x << endl;

      }

      cout << x << endl;

}

 

output

------

4

2

4

 

As I said, the scope of the variable is the top most block it is in. Blocks are signified by { }'s for the most part. So, within the first block (main's {}'s) x is created and initialized with the value of 4. Then, a new block is created and a new variable with the name x is created in static memory and takes the value of two. This is an entirely different memory location than the first x. Remember, the name of a variable is only a tool for people, the computer doesn't give a rats ass. One way to really see this is to display the address of the variable. The address is retrieved by using the & (called the "address of" operator) before a variable. Note what happens when we ask the computer to display the address of our variable x as well as its contents.

 

#include <iostream.h>

 

int main(void) {

      int x = 4;

      cout << x << "\t" << &x << endl;

      {

            int x = 2;

            cout << x << "\t" << &x << endl;

      }

      cout << x << "\t" << &x << endl;

}

 

output

------

4       0x0012FED4

2       0x0012FEC8

4       0x0012FED4

 

See how the second x has a different memory address than the first? A call to a variable will always get the variable in the top most scope. This may not seem very useful or important right now, but it becomes more apparent when using commands that involve blocks such as if statements or loops.


Tutorial Info
Written By: Gary Texmo a.k.a. Trinith
Written For: Omicron of http://www.bluesfear.com

Back to Bluesfear
Digital Art

2000, 2004© BlueSfear