Showing posts with label C #error. Show all posts
Showing posts with label C #error. Show all posts

Friday, July 13, 2018

C #error

Description

In the C Programming Language, the #error directive causes preprocessing to stop at the location where the directive is encountered. Information following the #error directive is output as a message prior to stopping preprocessing.

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.





#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
void main()
{
float a;
a=sqrt(7);
printf("%f",a);
}
#endif



Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.





#include<stdio.h>
#include<math.h>
#ifndef __MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif



Output:

2.645751

Example

Let's look at how to use #error directives in your C program.

The following example shows the output of the #error directive:





/* Example using #error directive by c programming */

#include <stdio.h>
#include <limits.h>

/*
* Calculate the number of milliseconds for the provided age in years
* Milliseconds = age in years * 365 days/year * 24 hours/day, 60 minutes/hour, 60 seconds/min, 1000 millisconds/sec
*/
#define MILLISECONDS(age) (age * 365 * 24 * 60 * 60 * 1000)

int main()
{
/* The age of C programming in milliseconds */
int age;

#if INT_MAX < MILLISECONDS(12)
#error Integer size cannot hold our age in milliseconds
#endif

/* Calculate the number of milliseconds in 12 years */
age = MILLISECONDS(12);

printf("TechOnTheNet is %d milliseconds old\n", age);

return 0;
}



In this example, we are using the int data type to hold the age of c programming in milliseconds. The int data type has a maximum value of INT_MAX which is defined in the limits.h header file and holds a value of 2^31 - 1 on both 32 and 64 bit systems. (See here for other variable types and their sizes.)

The statement #if INT_MAX < MILLISECONDS(12) evaluates whether or not the int data type is large enough to store the age in milliseconds. If it is not, the processor will output the following error message:





error: Integer size cannot hold our age in milliseconds



Since an error occurred, the program compilation will not complete and therefore no executable program will be created.

A typical use of the #error directive is to prevent compilation if a known condition exists that would cause the program to not function properly if the compilation completed. (For example, the C source was designed for a specific platform and was being compiled on an incompatible platform.)




Instagram