Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

10.2. What is it used for?

Macros are snippets of code that get processed before compilation. This is done by the C preprocessor, #define statements are macros. Take a look at this piece of code:

Example 10-1. box_of_stars.c

#define SIZE_OF_SQUARE 4

int
main()
{
  int i, j;

  for(i = 0; i < SIZE_OF_SQUARE; i++)
  {
    for(j = 0; j < SIZE_OF_SQUARE; j++)
    {
      printf("*"); // print an asterisk for each column
    }

    printf("\n"); // and a newline at the end of each row
  }
}
     
The output of this code will be a box:
****
****
****
****
    
The C preprocessor simply replaces the macro SIZE_OF_BOX with the value ``4''. This very useful for two reasons:

  • firstly the size of the box can be changed by just editing one line. This isn't a huge advantage in the above example as there are just two uses of SIZE_OF_BOX but in larger programs this make life much easier and removes the possibility of forgetting to change one of the values.

  • Secondly it makes the code more readable, meaningful names can be given to values such as #define PI 3.142857143.

 
 
  Published under the terms of the GNU General Public License Design by Interspire