Saturday, September 4, 2010

Object Oriented Language: C++, Variables and Data types

I have introduced the use of variables in the previous lesson. We are going into more details today.

// Variable declaration
int x;

// Variable initialization, the following two statements does the same thing, initialized the left-hand variable to 0
int y = 0;
int z(0); 

// Assignment statement
x = 22; 

// Play around with the variables
y = x = z; // guess what this does?



We'll talk about types of data types.

Source: http://www.desy.de/gna/html/cc/Tutorial/img20.gif

There is another predefined data type called bool, it has values true/false.
string is an add-on library to provide the language with the ability to store and manipulate a stream of characters.
int x = 100, y = 20, z = 10;
double pi(3.14);
float quarter = 0.25;

quarter = x; // this is fine
x = pi; // this would cause information to be truncated because integer cannot store decimal values. 

string aStr("Proving strongly/strictly typed");

// this would not compile because c++ is a strictly typed language.
x = aStr; // Compiler error, an integer variable cannot hold a string.

No comments:

Post a Comment