0

if we use

#define a 1 - MACROS or int a = 1 - Global variables before main function

what is the difference between the both of them assuming I won't alter the value of global variable?

1

#define a 1

Pre-processor will simply replace every occurrence of a in your source code with 1 before compilation. For instance, if you had a variable called myVar in your source file after preprocessing it will be changed to myV1r. One more time, this statement tells the preprocessor to literally replace every symbol a in your source file with a symbol 1. On a Linux machine you can use cpp source.c command to obtain preprocessed code.

int a = 1

Assuming that a is declared outside the main() and any function, at least 4 bytes will be allocated inside the data segment for it. The lifetime of such a variable is the entire runtime of the program. For automatic (local) variables memory space is allocated on stack and they are gone as soon as the execution of the function where they were declared finishes.

To get a closer look at memory allocation read this Wikipedia article: Data segment.

| improve this answer | |
-1

#define creates a pre-processor macro, those are inserted before compilation, and are no real variables. A global variable, however, is defined on the programme's stack, and you can create a pointer for it.

| improve this answer | |
  • No, what I'm asking is in both the cases will there be any change in my program after execution? – qwerty Nov 29 '16 at 14:14
  • Also, i think a global variable is defined in GLOBALS section of memory but not stack as mentioned in 'head first c' and Lloyd's lecture in cs50 – qwerty Nov 29 '16 at 14:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .