0
0
Cprogramming~10 mins

Define macro - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Define macro
Start
Preprocessor reads #define
Store macro name and replacement
Replace macro name with replacement in code
Compile replaced code
Run program
The C preprocessor reads the #define directive, stores the macro, replaces occurrences in code, then compilation and execution happen.
Execution Sample
C
#define PI 3.14
float area = PI * r * r;
Defines a macro PI as 3.14 and uses it to calculate area.
Execution Table
StepCode LineActionResulting Code
1#define PI 3.14Store macro PI with value 3.14No code output, macro stored
2float area = PI * r * r;Replace PI with 3.14float area = 3.14 * r * r;
3Compile replaced codeCompile float area = 3.14 * r * r;Ready to run
4Run programCalculate area using 3.14Area computed using 3.14
💡 All macros replaced, code compiled and executed
Variable Tracker
VariableStartAfter Macro ReplacementFinal
PIundefined3.143.14
areaundefinedundefinedcalculated value at runtime
Key Moments - 2 Insights
Why does the macro replacement happen before compilation?
Because the preprocessor runs first and replaces all macro names with their values before the compiler sees the code, as shown in execution_table step 2.
Is PI a variable that takes memory?
No, PI is just text replaced by 3.14 before compilation, so it does not use memory like a variable. See variable_tracker where PI is replaced.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table step 2, what does the code line become after macro replacement?
Afloat area = PI * r * r;
Bfloat area = 3 * r * r;
Cfloat area = 3.14 * r * r;
Dfloat area = r * r;
💡 Hint
Check the 'Resulting Code' column in step 2 of execution_table
At which step does the macro get stored by the preprocessor?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in execution_table step 1
If we change #define PI 3.14 to #define PI 3.14159, what changes in the execution_table?
AStep 1 macro storage changes to PI = 3.14
BStep 2 code becomes float area = 3.14159 * r * r;
CStep 3 compilation fails
DNo change at all
💡 Hint
Macro replacement in step 2 depends on the macro value stored in step 1
Concept Snapshot
#define MACRO_NAME replacement
- Defines a macro for text replacement
- Preprocessor replaces MACRO_NAME with replacement before compilation
- Macros do not use memory
- Useful for constants or code snippets
Full Transcript
In C, #define creates a macro that replaces text before compilation. The preprocessor reads the #define line, stores the macro name and its replacement text. Then, wherever the macro name appears in code, it is replaced by the replacement text. This happens before the compiler runs. For example, #define PI 3.14 replaces all PI with 3.14. Macros are not variables and do not take memory. The execution table shows storing the macro, replacing it in code, compiling, and running. This helps write readable and maintainable code.