Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Constants in C

In C programming, a constant is a value that cannot be modified during program execution. Constants are used to represent values that are known at compile-time and should not change, such as mathematical constants or program settings.

There are two ways to define constants in C programming: using the const keyword and using the #define preprocessor directive.

Defining Constants using const Keyword:

Constants can be declared using the const keyword followed by the data type and a name, and then assigned a value.

Here’s an example:

const float PI = 3.14159;

In this example, PI is a constant of type float with a value of 3.14159. The const keyword ensures that the value of PI cannot be changed during program execution.

Constants defined using const can be scoped just like any other variable in C programming.

For example, you can define a constant inside a function and use it only within that function.

Defining Constants using #define Preprocessor Directive:

The #define preprocessor directive is used to define constants in C programming.

Here’s an example:

#define PI 3.14159

In this example, PI is defined as a constant with a value of 3.14159. The #define directive tells the preprocessor to replace any occurrence of PI in the code with its value 3.14159.

Note that #define constants do not have a data type associated with them. Instead, the compiler determines the data type based on how the constant is used in the code.

Constants defined using #define are global and can be used throughout the program. Also, #define constants are not variables and do not take up any memory space.

Constants can be used in arithmetic expressions, function arguments, and more.

For example:

float circumference(float radius)
{
    return 2 * PI * radius;
}

Here, PI is used in an arithmetic expression to calculate the circumference of a circle with a given radius.