Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "defining" and "declaring" [duplicate]

Possible Duplicate:
What is the difference between a definition and a declaration?

I am trying to thoroughly understand "defining" and "declaring" in C.

I believe x here is defined, since external variables are automatically initialized to 0, and something that's declared and initialized is defined. Is that accurate?

int x;
main() {}

According to one x in this case is a definition, but why? It is not being initialized...

int print_hello()
{
  int x;
}
like image 310
user257412 Avatar asked Dec 10 '10 17:12

user257412


People also ask

What is the difference between defining and declaring?

Declaration means that variable is only declared and memory is allocated, but no value is set. However, definition means the variables has been initialized. The same works for variables, arrays, collections, etc.

What is the difference between declaring variable and using define?

Declaration vs Definition: In SummaryA declaration provides basic attributes of a symbol: its type and its name. A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored.

What is the difference between method declaration and method definition?

Like a class, a method definition has two major parts: the method declaration and the method body. The method declaration defines all the method's attributes, such as access level, return type, name, and arguments, as shown in the following figure. The method body is where all the action takes place.

What is difference between declaration definition and initialization?

Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.


1 Answers

Declaring is telling the compiler that there's a variable out there that looks like this.

Defining is telling the compiler that this is a variable.

One refers to the existence of a thing, the other is the thing.

In your example, the scope is what makes the difference. Declarations are made in a file scope, but in a block scope it is not possible to declare anything; therefore, the second example is a definition; because, there is nothing left to do with the int x;.

That makes the first example (in the file scope) a declaration that some int x; exists. To covert it from a declaration, you need to specify that a value is assigned to it, forcing the memory allocation. Like so: int x = 0;

C and C++ are very scope sensitive when it is analyzing constructs.

like image 123
Edwin Buck Avatar answered Sep 23 '22 04:09

Edwin Buck