Thursday, July 9, 2009

What is the difference between const keyword and #define for declaring constants in c language?

difference between


#define MAX 5


and const MAX=5

What is the difference between const keyword and #define for declaring constants in c language?
#define is a macro compiler


Const is a declaration of constant, compiler will do appropriate checks during the compile time.


#define is a macro compiler will see a value.


Speaking in terms of memory const declaration could be more efficient:


const int MAX=5;


so u can't change the value.


#define can also be given arguments which are used in its replacement. The definitions are then called macros
Reply:#define MAX 5;


const MAX = 5;


both are same in this case


the only difference comes when


#define sum(int x) { x=2+x; }


here we cannot use const


this is huge difference between them


thank u
Reply:const MAX=5 means the MAX variable would = 5, which woudl be constant, and you cant change the value. (of course, you would need to declare MAX as int or float if you were going to give it the value of 5.





#define MAX 5 is giving the word MAX a definition and the properties that you would use for it. You could change the value around, and it wouldnt necessary be constant, or, depending on how you use it, even an int or float value.
Reply:#define is a compiler directive. The value is assigned when you compile the program. The const MAX will be assigned at the run time.

wildflower

No comments:

Post a Comment