+ 23
What the best way to define a constant in c programmining languague?
what ixactly the difference between #define and cons ?
11 Antworten
+ 17
If you write "#define PI 3.14", all instances of PI in the program will be replaced with 3.14 by the preprocessor before compile time. If you write "const float PI=3.14", 3.14 will be stored in memory reserved for the constant PI and used at run time.
+ 11
#define is a preprocessor directive which creates a macro. 'const' is a C/C++ keyword used to create a constant variable. The usage of the latter is in general a better practice wherever applicable.
+ 7
#define PI 3.14:
Preprocessor replace al the occurences of "PI" with 3.14 before the program is compiled
-----------------------
const float PI = 3.14:
Create a variable (stored in memory) that is not modifiable
+ 6
Const type qualifier.
Object declared with const-qualified types may be placed in read-only memory by the compiler, and if the address of a const object is never taken in program, it may not be stored at all in a data segment, but only in a code/text segment. And there are two types of constants: compiler-time and run-time, so they have different behavior.
+ 5
Nobody has mentioned about important issue connected with preprocesor directives. If You will use:
#define PI 3.14
and u will write in your code statement like:
PIE = PI + 2
The output after preprocessing will be like:
3.14E = 3.14 +2
... and the error will occur.
Be careful while using preprocessor directives! :)
Preprocessors '#define' sees the whole code as plain TEXT, without applying any logic.
+ 4
Thanks Krzych, As you pointed out, the preprocessor when invoked by #define PI 3.14 only looks at the text not the program as a whole.
and this would cause strange errors as it changed all the "PI"s in your code to "3.14"s. That why you see "#define"s followed by all capital letters. and everything else is lower or mixed case letters.
+ 2
U can actually use a preprocessor directory i.e #define (variable) (constant value)
So the whole code will consider the variable as a contant...
For example #define PI 3.14
Note: keep in mind that once the constant is defined then u CANNOT change its value throughout the code...
+ 1
ymy
0
#define PI 3.14; this allows you to access it's value while making const the value got fixed and stored in memory for further access
0
#define value
or const value
0
#define pi=3.1416