VOOZH about

URL: https://www.geeksforgeeks.org/c/different-ways-declare-variable-constant-c-c/

⇱ Different ways to declare variable as constant in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Different ways to declare variable as constant in C

Last Updated : 10 Jun, 2024

There are many different ways to make the variable as constant in C. Some of the popular ones are:

  1. Using const Keyword
  2. Using Macros
  3. Using enum Keyword

1. Using const Keyword

The const keyword specifies that a variable or object value is constant and can't be modified at the compilation time.

Syntax

const data_type variable_name = initial_value;

Example

The below example demonstrates use of the const keyword.

It will throw as error like:
error: assignment of read-only variable ‘num’

2. Using Macros

We can also use Macros to define constant, but there is a catch. Since Macros are handled by the pre-processor(the pre-processor does text replacement in our source file, replacing all occurrences of 'var' with the literal 5) not by the compiler. Hence it wouldn't be recommended because Macros doesn't carry type checking information and also prone to error. In fact not quite constant as 'var' can be redefined like this.

Syntax

#define name value

Example

The below example demonstrates use of macros (#define).


Output
5 10

Note:preprocessor and enum only works as a literal constant and integers constant respectively. Hence they only define the symbolic name of constant. Therefore if you need a constant variable with a specific memory address use either 'const' or 'constexpr' according to the requirement.

3. Using enum Keyword

Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, that make a program easy to read and maintain.

Example

The below example demonstrates use of the enum keyword.


Output
The value of var: 42

Note: The data types of enum are of course limited as we can see in above example.


Comment
Article Tags: