Const data type

This lesser known data type is used to declare constants.The syntax isconst type name=value;
ex:
const int a=10;
is equivalent to
#define a 10
now consider this program
#include<stdio.h>

void main() 

const int a=10;
printf("%d",a);
a=14;
printf("%d",a);
}


void main()
{
const int a=10;
printf("%d",a);
printf("Enter new value\n");
scanf("%d",&a);
printf("The value is now %d",a);
}
#define a 10
void main()
{
printf("%d",a);
printf("Enter new value\n");
scanf("%d",&a);
printf("The value is now %d",a);
}


 So, the difference between const and #define is that we can change the value of the constant during runtime execution if we use const where as we are unable to do so if we use #define.
const char a[10]={"adithya"};/*String*/
const float a=4.67;/*float*/
const long double a=9.78843434;/*long double*/
1.I have tested these in Turbo C for windows.Earlier versions of C will not support this datatype.
2.The constants created by using const is called as static constant.If you want your constant to be both dynamic as well as static,the only way is to use #define

what do you think the ouput will be???

First off all the program will not compile itself because it is not allowed to change the value of 'a' statically(within the program)
now change the program as
#include<stdio.h>
will change the value of a

That means we can change the value of the constant declared by using const in run time mode(Dynamically) but not Statically(within the program).

now consider this program
#include<stdio.h>
what do you think the output will be???
the program will not be compiled,that means that we can access the value of 'a' but not able to use scanf.
The use of const is not restricted to int only.

ex: 
const char a='y';/*char*/
now you can say that all these can be done using #define also.

But there are several things for which we cannot use #define
The excellent example is array.

Can anyone tell me how to declare an static constant array using #define???

But i can tell you how to do so using const
const float a[10]={1,3,5};
Note:

About This Blog

There is something for everyone. !! A tech blog on various topics. Let it be devops, programming etc; we have it all covered here in layman terms :)

Total Pageviews

Back to TOP