Preprocessors

One way in which constants can be declared in C, as previously stated is using “const”.

 const int PI = 3.14159;

An alternative way to do this, is using something called a preprocessor directive. This is a piece of code that you will write at the very top.

 #define PI 3.14159

The lines beginning with the hash symbol (#) are not C statements. Notice that the #define statement doesn’t end in a semicolon, also there is no “=” sign between the identifier, PI, and the value, 3.14159.
These statements are rather referred to as preprocessor directives. The preprocessor goes through the code before compilation begins, and replaces every instance of, in this case, MYCONST with 23.
Hence, if you’re writing a program that uses pi, you write the line:

 #define PI 3.14159

At the top, and then everywhere where the value 3.14 is required, you write PI.
Once you run the command to compile your source code, the preprocessor goes through your code and replaces every instance of PI with 3.14159.
This is different from using:

 const int PI = 3.14159;

When using the const int, it works like any regular integer, the only exception being that if you try to assign PI a different value in your code, the compiler will throw an error.
With the preprocessor directive PI, it is essentially a placeholder for the number 3.14159.

Libraries

    • Another important use of the preprocessor directive is the

 

 #include

 

    • In the C programming language, there are a lot of commonly used functions, such as input/output operations. Since no one wants to write a function that takes input from the keyboard, or displays output to the display, we can use already implemented once. Similarly many other such functions already exist and are readily available through the include directive.

 

    • For the I/O functions you need to include the standard input output library, like so.

 

 #include <stdio.h>

 

    Note that these libraries all end in a “.h”, they are called header files. Later we will learn that you can write your own header files.

Next Page: Input, Output; and writing your first program

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s