Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between global variables and #define in c

Whats the reason why there are 2 opportunities :

  1. global variables
  2. symbolic constants with #define ?

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.

like image 811
Clock_9 Avatar asked May 02 '15 09:05

Clock_9


2 Answers

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
#ifdef __linux__
    #define WELCOME_STRING "welcome to Linux!"
#else
    #define WELCOME_STRING "welcome to Windows!"
#endif

// Example with hardware
#if __x86_64__ || __ppc64__
    #define USING_64BIT
#else
    #define USING_NOT64BIT
#endif
like image 118
FalconUA Avatar answered Sep 24 '22 23:09

FalconUA


Consider this small example

#define num 5
int number = 5;

num is a macro and number is a global variable.

One important difference is that num is not stored in the memory, num is just the substitute for 5, but number uses memory.

Also, macro's are preprocessor directives, their values cannot be changed like variables.

So, no doing

num = 6;

later in the code. You will have to use #undef to undefine it and define it again to change the value.

like image 24
Arun A S Avatar answered Sep 24 '22 23:09

Arun A S