1.

What is the difference between declaration and definition for a variable or a function in C?

Answer»

The declaration of a variable or function simply STATES that it EXISTS at some place in the program but that no memory has been allocated for it. The declaration of a variable or function is crucial because it INFORMS the program about the type of the variable or function. It also tells the program the arguments, their data types, the order of those arguments, and the function's return type in the case of function declarations. That concludes the declaration.

In relation to the definition, defining a variable or function does more than just DECLARE it; it also allocates memory for that variable or function. As a result, we can consider declaration to be a subset of definition (or declaration as a SUPERSET of definition).

Variable:

A variable is defined and declared at the same time in the C programming language. There is no distinction between declaration and definition for a variable in C, in other words.

Example:

int x;

The information, such as the variable name: x and the data type: int, is passed to the compiler and is saved in the symbol table data structure. A memory of size 2 bytes will also be allocated (depending on the type of compiler).

If we merely want to declare variables and not define them, i.e. we don't want to allocate memory space, we can use the following declaration:

extern int x;

Only the information about the variable is sent in this example, and no memory is allocated. The above information informs the compiler that variable an is declared now, but memory for it will be defined later, either in the same file or in a separate file.

Function:

The function declaration provides to the compiler, the name of the function, the number and type of arguments it accepts, and the return type. Consider the following code, for example:

int sum (int, int);

A function named sum is declared with two int arguments and an int return type. At this time, no memory will be allocated.

Allocating memory for the function is based on the function's definition. Consider the following function definition, for example:

int sum (int x, int y) { return (x+y); }

The memory for the function add will be allocated during this function definition. A variable or function can be declared as many times as needed, but it can only be defined once.



Discussion

No Comment Found