Whats the reason why there are 2 opportunities :
- global variables
- symbolic constants with
So I know what
#define does but I don't know what the difference in use is. Which situation do I must have thus I'm able to decide myself upon the right opportunitie? What is one of the opportunities able to do what the other one doesn't ? I hope that I could clarify what I mean.
Best How To :
Well, global variables can be edited from everywhere.
Basically, in the low level, a variable is stored in RAM memory and created after launching your application, it always has an address in RAM. Defines are just macros, your compiler will just replace your define names with its values in the compilation step.
#define can't be edited, it's just a macros. And
#define is not just about values, you can define almost everything that you want, for example:
// Defining a constant
#define PI 3.14
// Defining an expression
#define MIN(x,y) ((x)<(y))?(x):(y)
// Defining a piece of code
#define STOP_TIMER \
clock_gettime(CLOCK_REALTIME, &__t1); \
__lasttime = \
(double) (__t1.tv_sec - __t0.tv_sec) + \
(double) (__t1.tv_nsec - __t0.tv_nsec) / 1000000000.0;
And, in most situations, defines are used to set some OS-specific or hardware-specific values. It's a really powerful thing, because it gives you the opportunity to change things dynamically in the compilation step. For example:
// Example with OS
#define WELCOME_STRING "welcome to Linux!"
#define WELCOME_STRING "welcome to Windows!"
// Example with hardware
#if __x86_64__ || __ppc64__