+ 1

What is the difference between declaration and definition of a variable/function?

31st Mar 2018, 9:20 AM
pushpendra kumar
pushpendra kumar - avatar
4 Respostas
+ 3
The declaration alone can be a placeholder so that the compiler knows the function exists. The definition is the actual logic of the function. void function(); int main(){ function(); return 1; } void function(){ //code }
31st Mar 2018, 9:27 AM
Alex
Alex - avatar
+ 2
correct me if I'm wrong... declaration of variable is allocating a memory location /reserving a space in memory. defining a function/method is simply creating a function. you specify the name, parameters, return type if not, void and the body which will contain the actual operations to carry out to come up with the desired output...
31st Mar 2018, 9:55 AM
Heji Palaña
Heji Palaña - avatar
+ 1
When you declare a variable, a function, or even a class all you are doing is saying: there is something with this name, and it has this type. The compiler can then handle most (but not all) uses of that name without needing the full definition of that name. Declaring a value--without defining it--allows you to write code that the compiler can understand without having to put all of the details. This is particularly useful if you are working with multiple source files, and you need to use a function in multiple files. You don't want to put the body of the function in multiple files, but you do need to provide a declaration for it. Defining something means providing all of the necessary information to create that thing in its entirety. Defining a function means providing a function body; defining a class means giving all of the methods of the class and the fields. Once something is defined, that also counts as declaring it; so you can often both declare and define a function, class or variable at the same time. But you don't have to.
6th Apr 2018, 1:17 PM
pushpendra kumar
pushpendra kumar - avatar
0
void also need to be specified in the definition. But beside that you are right. int i; //declaring variable void func(); //declaring function i=5; //define variable void func(){ ... } //define function
31st Mar 2018, 10:09 AM
Alex
Alex - avatar