Friday, January 11, 2013

How to create Constants in C

C Language: Create Constants using #define (macro definition)

In the C Programming Language, you can define constants using the macro definition or #define syntax. You generally use this syntax when creating constants that represent numbers or characters.

Syntax

The syntax for creating a constant using #define is:
#define CNAME value
or
#define CNAME (expression)
CNAME is the name of the constant. Most C programmers define their constant names in uppercase, but it is not a requirement of the C Language.
value is the value of the constant.
expression is an expression whose value is assigned to the constant. The expression must be enclosed in brackets if it contains operators.

Note

  • Do NOT put a semicolon character at the end of this statement. This is a common mistake.

Example #1 - Defining a constant using a value

You can define an integer constant (using a value) as follows:
#define AGE 10
In this example, the constant named AGE would contain the value of 10.
You can define a string constant (using a value) as follows:
#define NAME "TechOnTheNet.com"
In this example, the constant called NAME would contain the value of "TechOnTheNet.com".
Below is an example C program where we define these two constants:
#include <stdio.h>

#define NAME "TechOnTheNet.com"
#define AGE 10

int main()
{
   printf("%s is over %d years old.\n", NAME, AGE);
   return 0;
}
This C program would print "TechOnTheNet.com is over 10 years old."

Example #2 - Defining a constant using an expression

You can define a constant (using an expression) as follows:
#define AGE (20 / 2)
In this example, the constant named AGE would also contain the value of 10.
Below is an example C program where we define this constant:
#include <stdio.h>

#define AGE (20 / 2)

int main()
{
   printf("TechOnTheNet.com is over %d years old.\n", AGE);
   return 0;
}
This C program would also print "TechOnTheNet.com is over 10 years old."

No comments:

Post a Comment