Declaring vs Defining variables

Started by magesh.p, Apr 27, 2009, 09:19 PM

Previous topic - Next topic

magesh.p

Declaring vs Defining variables

In C++, there are 2 ways of introducing variables. The first way is called declaration of a variable. The second is called definition of a variable. The following code snippet shows the differences:

int i; //declaration of i as type int
int i = 5; //definition of variable i and assigning value 5 to it
string s;         //declaration of s as type string
s = "Hello World; //assigning "Hello World" to s
string s2 = "Hello Reader"; //definition of s as string with value "Hello Reader



Note that, when assigning values to variables, you need to make sure that the value is a valid value . This means that, when, for example, you define a variable of type int you have to make sure that the value you assign to it is an integer.

Quoteint i;
i = 5; //correct! 5 is integer

int j;
j = "Hello World" //wrong! j is not a string

double d;
d = 3.145; //correct! 3.145 is a double

int k;
k = 1.23456; //wrong! 1.23456 is not an int


If you assing wrong values to variables of another data type, the compiler will complain an error.

Defining a variable means to declare it and assign a value to it.

Declaring a variable means only to introduce it to the compiler.
- An Proud Acumen -

Quick Reply

Warning: this topic has not been posted in for at least 120 days.
Unless you're sure you want to reply, please consider starting a new topic.

Note: this post will not display until it has been approved by a moderator.

Name:
Email:
Verification:
Please leave this box empty:
Type the letters shown in the picture
Listen to the letters / Request another image

Type the letters shown in the picture:

Shortcuts: ALT+S post or ALT+P preview