Monday 29 May 2017

c - Difference between "defining" and "declaring"

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.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...