Auto and Extern in C

Hello coders! Welcome back!

Today lets look at what are auto and extern in C.

Auto and extern are kind of modifiers. Auto means automatic and extern means external.

Variables that are declared inside the function/ scope are referred to as automatic variables. Because once the execution of the function is over, the variables get destroyed. From the previous blog, we have seen that the scope of the variable is within that function(click here to view that blog) hence they are called automatic variables.

Advantage:-  Automatic variables won't waste any memory. After execution, the memory gets de-allocated. 

By default variables are auto. And it returns garbage value if it is not initialized

So, we can see that it prints a garbage value. 

Global variables are also auto by default. They won't produce garbage value instead they get initialize to zero.

Hence you can see that by default global variables get initialized to zero.

If I declare -
int varr 
It's like declaring and defining, means allocating memory to that variable. 

If I declare-
extern int varr
It's like declaring but not defining means not allocating memory to it. 

What is the need for an extern modifier?

If you are building a project, a particular variable needs to be accessed from another file then we use an extern variable.

let's look into code for more clarity- 

Here, you can see that I have created a project named 'program'. It contains sources file-
 main.c and other.c files.

The above code is present in main.c file. 'extern int a' searches for value of 'a' that is present in other.c file.

other.c file contains value of variable 'a'. Now, let's look at output whether it produces required output or not

So the extern modifier takes the value from other.c file and produces the required result.

Let's look into another example. when extern is declared inside the function-

We can see that it displays the value of the global variable. Hence extern variable says that go outside my scope you will find the value.

It reuses the variable name that is present in some other file or that is present outside its scope.

A linker is used to combine the files and link those references or variables.

In extern, multiple declarations are allowed but not multiple definitions.

I hope so you got what are auto and extern modifiers in C. If any doubts drop a comment.


Happy learning!

Comments

Popular post