Question:
What's the difference b/w 'declaring and defining' the variables?
SS
2010-12-17 12:23:39 UTC
What's the difference b/w 'declaring and defining' the variables practically?

I read the this definition;
"In declaring, just the data types are mentioned without any memory storage for the data types. While defining the variable the declaring the data type of the variable along with space allocation for the variable takes place."

But yet I don't understand while in program where we are just declaring the variable or where we are defining it? For example,

int var1;
char var2;
//Here we are declaring the variable

var1=1;
var2=c;
// Here we are defining it

int var1=1;
char var2=c;
//Here we are declaring and defining the variables at the same time

Is it really meant that? Am I correct?
*If there are any grammar mistakes please correct them, I also have to improve my english;) Thanks*
Four answers:
lansingstudent09101
2010-12-17 12:28:04 UTC
Yes, this is what is meant.



To be more technical, the name is installed in the symbol table at the declaration. This tells the compiler that it is the first use of the variable, and not an erroneous misspelling of a previous variable. It also gives the compiler the type for the variable, which makes compiling much easier.



There are languages where declarations are optional (PHP for instance).
2010-12-19 01:15:35 UTC
Yeah, M.Saad, that's pretty much it. What language are you using? I ask because one of the immediately visible differences between C and C++ is that in C all local variables within a function must be declared at the beginning of the function before any executable code, while in C++ you can freely mix code and declarations.



For example, this is valid in C++ but not C:



int function()

{

int local1 = 54;

other_function(local1);



char digit = another_function(); // compiler error!

return 0;

}



Initializing is the same thing as defining.
Jacob D
2010-12-17 20:25:03 UTC
You are correct in your examples. You are correctly defining and declaring your variables.
2010-12-17 20:27:00 UTC
Defining is when you explicitly tell your compiler or interpreter the data type of your variable.



Declaring variables is when assign values to your defined variables for the first time so that their values are not arbitrary.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...