In this article, I will explain two most important concepts in C language that are very often confused by beginner embedded developers. I will explain what each of them means and what is the key difference, so from now on you won’t confuse them
Let’s start with the declaration term. This is the information for the compiler that some objects like for example function exists, and have a certain name and properties. By properties I mean a type of data stored in a variable or a type of value returned by function. That’s all. At this point, there is no memory allocation because, in fact, the actual object doesn’t exist. What exists is information on what the potential would look like if it existed. Here are some examples
extern int a;
int add_two_numbers(int x, int y);
Let’s move now to the definition concept. In C language it differs a bit for variables and functions. Let’s explain it for functions first. To put it very simply, we can say that the definition is an extended declaration because we have here the same information about the name and parameters. But that’s not all. In this case, we define exactly what this object is, what task it has to do and how to perform it, and most importantly, reserve memory for it. Here is the „add_two_numbers” function definition:
int add_two_numbers(int x, int y)
{
int result = x + y;
return result;
}
For most variables ( except extern ) declaration is the same as definition. Of course, we can differentiate a variable declaration as:
int var;
from variable declaration
var = 5;
or both at the same time:
int var = 5;
but as I said before, except for the „extern” declaration, even if we do not assign explicitly a value to the variable, the declaration is also a definition because always there is a default value assigned. Most of the time is the zero value (global and static variables), but it could be also some random value taken from the stack (for local scope variables). No matter what the value will be, there is a memory space assigned to it, so it’s not only an empty declaration.
The extern keyword is different, in this case, this is just an empty declaration but this and when and why there a default values assigned to variables I will explain in a different post.
To sum up the topic, there is a difference between declaration and definition, so you should not confuse them anymore. The key difference is memory consumption. The declaration is just empty information for the compiler (no memory is used at this point). The definition creates an „object” so memory must be allocated.