Sunteți pe pagina 1din 13

#define Directive (macro definition)

This C tutorial explains how to use the #define preprocessor directive in the C language.

Description
In the C Programming Language, the #define directive allows the definition of macros within
your source code. These macro definitions allow constant values to be declared for use
throughout your code.
Macro definitions are not variables and cannot be changed by your program code like
variables. You generally use this syntax when creating constants that represent numbers,
strings or expressions.

Syntax
The syntax for creating a constant using #define in the C language is:

#define CNAME value

OR

#define CNAME (expression)

CNAME

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

The value of the constant.

expression

Expression whose value is assigned to the constant. The expression must be enclosed
in parentheses if it contains operators.

Note

 Do NOT put a semicolon character at the end of #define statements. This is a common
mistake.

Example
Let's look at how to use #define directives with numbers, strings, and expressions.
Number

The following is an example of how you use the #define directive to define a numeric
constant:

#define AGE 10

In this example, the constant named AGE would contain the value of 10.

String

You can use the #define directive to define a string constant.


For example:

#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 the following:

TechOnTheNet.com is over 10 years old.

Expression

You can use the #define directive to define a constant using an expression.
For example:
#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 use an expression to define the 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 the following:

TechOnTheNet.com is over 10 years old.

Macros using #define

You can define a macro in C using #define preprocessor directive.

A macro is a fragment of code that is given a name. You can use that fragment of code in
your program by using the name. For example,

#define c 299792458 // speed of light

Here, when we use c in our program, it's replaced by 3.1415.

Example 1: Using #define preprocessor

#include <stdio.h>
#define PI 3.1415

int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%d", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}

You can also define macros that works like a function call, known as function-like macros.
For example,

#define circleArea(r) (3.1415*r*r)

Every time the program encounters circleArea(argument), it is replaced


by (3.1415*(argument)*(argument)).

Suppose, we passed 5 as an argument then, it expands as below:

circleArea(5) expands to (3.1415*5*5)

Example 2: Using #define preprocessor

#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)

int main()
{
int radius;
float area;

printf("Enter the radius: ");


scanf("%d", &radius);
area = circleArea(radius);
printf("Area = %.2f", area);

return 0;
}

Predefined Macros

There are some predefined macros which are readily for use in C programming.

Predefined macro Value

__DATE__ String containing the current date

__FILE__ String containing the file name

__LINE__ Integer representing the current line number

__STDC__ If follows ANSI standard C, then value is a nonzero integer

__TIME__ String containing the current date.

Example #3: predefined Macros

C Program to find the current time

#include <stdio.h>
int main()
{
printf("Current time: %s",__TIME__); //calculate the current time
}

Output

Current time: 19:54:39


C Language: #undef Directive
This C tutorial explains how to use the #undef preprocessor directive in the C language.

Description
In the C Programming Language, the #undef directive tells the preprocessor to remove all
definitions for the specified macro. A macro can be redefined after it has been removed by
the #undef directive.
Once a macro is undefined, an #ifdef directive on that macro will evaluate to false.

Syntax
The syntax for the #undef directive in the C language is:

#undef macro_definition

macro_definition

The name of the macro which will be removed by the preprocessor.

Example
The following example shows how to use the #undef directive:

/* Example using #undef directive by TechOnTheNet.com */

#include <stdio.h>

#define YEARS_OLD 12

#undef YEARS_OLD

int main()
{
#ifdef YEARS_OLD
printf("TechOnTheNet is over %d years old.\n", YEARS_OLD);
#endif
printf("TechOnTheNet is a great resource.\n");

return 0;
}

In this example, the YEARS_OLD macro is first defined with a value of 12 and then
undefined using the #undef directive. Since the macro no longer exists, the statement #ifdef
YEARS_OLD evaluates to false. This causes the subsequent printf function to be skipped.
Here is the output of the executable program:

TechOnTheNet is a great resource.

#if and #else

Conditional compilation in C programming language: Conditional compilation as the name


implies that the code is compiled if certain condition(s) hold true. Normally we use if
keyword for checking some condition so we have to use something different so that compiler
can determine whether to compile the code or not. The different thing is #if.

Now consider the following code to quickly understand the scenario:

C programming code

#include <stdio.h>

#define x 10

int main()
{
#ifdef x
printf("hello\n"); // this is compiled as x is defined
#else
printf("bye\n"); // this is not compiled
#endif

return 0;
}

Conditional compilation example in C language

#include <stdio.h>

int main()
{
#define COMPUTER "An amazing device"

#ifdef COMPUTER
printf(COMPUTER);
#endif

return 0;
}

C Language: #ifdef Directive


This C tutorial explains how to use the #ifdef preprocessor directive in the C language.

Description
In the C Programming Language, the #ifdef directive allows for conditional compilation. The
preprocessor determines if the provided macro exists before including the subsequent code in
the compilation process.

Syntax
The syntax for the #ifdef directive in the C language is:

#ifdef macro_definition

macro_definition

The macro definition that must be defined for the preprocessor to include the C source
code into the compiled application.
Note

 The #ifdef directive must be closed by an #endif directive.

Example
The following example shows how to use the #ifdef directive in the C language:

/* Example using #ifdef directive by TechOnTheNet.com */

#include <stdio.h>

#define YEARS_OLD 10

int main()
{
#ifdef YEARS_OLD
printf("TechOnTheNet is over %d years old.\n", YEARS_OLD);
#endif

printf("TechOnTheNet is a great resource.\n");

return 0;
}

Here is the output of the executable program:

TechOnTheNet is over 10 years old.


TechOnTheNet is a great resource.

A common use for the #ifdef directive is to enable the insertion of platform specific source
code into a program.
The following is an example of this:

/* Example using #ifdef directive for inserting platform specific source code by
TechOnTheNet.com */
#include <stdio.h>

#define UNIX 1

int main()
{
#ifdef UNIX
printf("UNIX specific function calls go here.\n");
#endif

printf("TechOnTheNet is over 10 years old.\n");

return 0;
}

The output of this program is:

UNIX specific function calls go here.


TechOnTheNet is over 10 years old.

In this example, the UNIX source code is enabled. To disable the UNIX source code, change
the line #define UNIX 1 to #define UNIX 0.

#ifndef statement : Conditional Compilation Directives (C Preprocessor)

What it does ?

 These Conditional Compilation Directives allow us to include certain portion of the


code depending upon the output of constant expression
 Block is Called as Conditional Group

Syntax :

#ifndef MACRONAME
Statement_block;
#endif
Explanation :

1. If the MACRONAME specified after #ifndef is not defined previously in #define then

statement_block is followed otherwise it is skipped


2. We say that the conditional succeeds if MACRO is not defined, fails if it is not.

Live Example 1 :

#include"stdio.h"

void main()
{
// Define another macro if MACRO NUM is defined

#ifndef NUM
#define MAX 20
#endif

printf("MAX number is : %d",MAX);


}

Output :

MAX Number is 20

Variable arguments in a function

Sometimes, you may come across a situation, when you want to have a function, which can
take variable number of arguments, i.e., parameters, instead of predefined number of
parameters. The C programming language provides a solution for this situation and you are
allowed to define a function which can accept variable number of parameters based on your
requirement.
To use such functionality, you need to make use of stdarg.h header file which provides the
functions and macros to implement the functionality of variable arguments and follow the
given steps −

 Define a function with its last parameter as ellipses and the one just before the
ellipses is always an int which will represent the number of arguments.

 Create a va_list type variable in the function definition. This type is defined in
stdarg.h header file.

 Use int parameter and va_start macro to initialize the va_listvariable to an argument
list. The macro va_start is defined in stdarg.h header file.

 Use va_arg macro and va_list variable to access each item in argument list.

 Use a macro va_end to clean up the memory assigned to va_listvariable.

Now let us follow the above steps and write down a simple function which can take the
variable number of parameters and return their average −
Live Demo

#include <stdio.h>

#include <stdarg.h>

double average(int num,...) {

va_list valist;

double sum = 0.0;

int i;

/* initialize valist for num number of arguments */

va_start(valist, num);

/* access all the arguments assigned to valist */

for (i = 0; i < num; i++) {

sum =sum + va_arg(valist, int);


}

/* clean memory reserved for valist */

va_end(valist);

return sum/num;

int main() {

printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));

printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));

When the above code is compiled and executed, it produces the following result. It should
be noted that the function average() has been called twice and each time the first argument
represents the total number of variable arguments being passed. Only ellipses will be used to
pass variable number of arguments.

Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000

S-ar putea să vă placă și