www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C Tutorial - Lesson 3: Constants

Declaring and Using Constants

by John Kopp

Support this site at no cost to you

Welcome to easyCPlusPlus.com's C tutorial. This lesson will teach you how to declare and use constants in C. A constant is similar to a variable in the sense that it represents a memory location. It differs, as I sure you can guess, in that it cannot be reassigned a new value after initialization. In general, constants are a useful feature that can prevent program bugs and logic errors. Unintended modifications are prevented from occurring. The compiler will catch attempts to reassign new values to constants.

Using #define
There are three techniques used to define constants in C. First, constants may be defined using the preprocessor directive #define. The preprocessor is a program that modifies your source file prior to compilation. Common preprocessor directives are #include, which is used to include additional code into your source file, #define, which is used to define a constant and #if/#endif, which can be used to conditionally determine which parts of your code will be compiled. The #define directive is used as follows.

#define pi 3.1415
#define id_no 12345

Wherever the constant appears in your source file, the preprocessor replaces it by its value. So, for instance, every "pi" in your source code will be replace by 3.1415. The compiler will only see the value 3.1415 in your code, not "pi". Every "pi" is just replaced by its value. Here is a simple program illustrating the preprocessor directive #define.

#include <stdio.h>

#define monday 1
#define tuesday 2
#define wednesday 3
#define thursday 4
#define friday 5
#define saturday 6
#define sunday 7

int main()
{

    int today = monday;

    if ((today == saturday) || (today == sunday))

    {
         printf("Weekend\n");
    }
    else
    {
        printf("Go to work or school\n");
    }

    return 0;
}

Using const variables

The second technique is to use the keyword const when defining a variable. When used the compiler will catch attempts to modify variables that have been declared const.

const float pi = 3.1415;
const int id_no = 12345;

There are two main advantages over the first technique. First, the type of the constant is defined. "pi" is float. "id_no" is int. This allows some type checking by the compiler. Second, these constants are variables with a definite scope. The scope of a variable relates to parts of your program in which it is defined. Some variables may exist only in certain functions or in certain blocks of code. You may want to use "id_no" in one function and a completely unrelated "id_no" in your main program. Sorry if this is confusing, the scope of variables will be covered in a latter lesson.

Previous Page       Next Page