constant in C

Hello coders! Welcome back!

Today we are going to have a look at constants in c language.

Constant are those variables that are never going to change.

We can define constants in two ways-

  •  By using #define. 
  • By using the 'const' keyword. 
Let's look into the first type. The syntax for this is-
#define <NAME> <value> 

The name is also treated as a macro.


This is how we define constant using #define.

It's important to note that, there is no semicolon at the end of the #define statement.

The job of the preprocessor is to replace the name 'PI' with the value. Note that the preprocessor does this job, not the compiler.

It's recommended to use the capital alphabets for the name. So that we can use the same name as a local variable in our code.

The name given is equivalent to macros. we look into macros in-depth in later blogs

We can use macros as functions too. Let's look into the example-


I have defined the macro named add. Keep in mind not to give space between add and brackets of the parameter. Inside the main function, I'm passing values of x and y as 3 and 4 respectively. The preprocessor replaces the value and prints the value.

We can write multiple lines using '\'. Let's look into the program-


You can see that I have created multiple lines macro or you can call it as constant. And in the main function, I'm passing the values to compare. And its returning correct statements according to the value.

Always define instructions are expanded first and then evaluated. Let's look at the code- 


You are going to expect the answer to be as 25. As many of you commit mistake here itself. You are performing addition separately and then multiplying it by 5.

NO!! doing like that is wrong. As said preprocessor is going to replace the values. It is not going to perform any operation. 

Actually what happening is it replace the value and the equation becomes as-
result = 5*2+3
It follows the BODMAS rule and gives the output as 13.


There are few built-in macros or definitions such as to print the current date and time. Let's look at their code too-


It's important to mention them as it is, all in capital alphabets with two underscores on either side, only then it's going to produce exact results.

Next will look at the const keyword.
Syntax of it is-
const <data_type> <variable_name>
In const keyword, once a variable is declared we cant replace it with another value. It is like 'read-only value'

Let's look into the code what happens if we try to replace the value- 


So, you can see that it's going to give an error.

So what's the difference between static and const keyword?

Static is going to retain the previous value and gets updated if any operation is performed. Whereas the const keyword doesn't change its value even if you are going to perform any operation.

So that's it for this blog!! If any doubts drop a comment.

Happy learning!

Comments

Popular post