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?
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.Sign up to join this community
#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
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.