C #define

Description

Preprocessor directives can replace symbols in source code before it is compiled.

Syntax

The general form of this sort of preprocessor directive is the following:

#define identifier sequence_of_characters

Example

For example, we use preprocessor directive to define a string PI as 3.14159265.

#define PI 3.14159265

Then the preprocessor directive substitutes the specified numeric value, wherever the character string PI occurs.

After preprocessing has been completed, the string PI will no longer appear. The PI is replaced by 3.14159265.


#include <stdio.h>
/*from   w w w .j  av  a  2s.co  m*/
#define  PI 3.14159f                  /* Definition of the symbol PI */

void main()
{
   float radius = 0.0f;
   float diameter = 2.0f;
   float circumference = 0.0f;
   float area = 0.0f;

   radius = diameter/2.0f;
   circumference = 2.0f*PI*radius;
   area = PI*radius*radius;
   printf("\nThe circumference is %.2f", circumference);
   printf("\nThe area is %.2f", area);
}

Note

Here, identifier can be any sequence of letters and digits. The first letter of identifier must be a letter, and underline characters count as letters.

sequence_of_characters, which is the replacement for identifier, need not be just digits.

Example 2

Use preprocessor to define integer and string


#include <stdio.h>
/*www .j  a v  a2  s.  co m*/
#define VAL 35
#define HELLO "HELLO"

main ()
{
    int res;

    res = VAL-5;
    printf ("res = VAL-5: res == %d\n", res);
    printf ("%s",HELLO);
}

The code above generates the following result.





















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing