×

Different ways to Declare the Variable as Constant in C

There are a wide range of ways of making the variable as steady

Using const keyword:

The const catchphrase permits a software engineer to inform the compiler that a specific variable should not be changed after the underlying task in its statement. On the off chance that any code attempts to dole out another worth to that factor, the compiler will produce a blunder "Task to peruse just factor not permitted," showing that the task activity should not happen. This permits a developer to forestall undesirable adjustments to factors that should not be changed for unknown reasons. Note that const factors should be instated; in any case, there could be no alternate method for allocating them values.

Coming up next is an illustration of a straightforward statement of a consistent number:

const int n = 42;

Note that the const in the above statement can likewise come after the sort, as in the accompanying:

int const n = 42;

In a straightforward const variable statement, any capacity type might be utilized. It is feasible to have an auto-const variable; it implies that the worth is put away on the stack and can't be altered. Basic const statements should presumably be static (this isn't true with pointers, as we will see underneath). Are constants non? Modifiable so different gets to (say using a? entrant capability) will all be perused, making a solitary stockpiling area desirable over distributing space for the consistent on the stack for each call. The ramifications are that a nearby const ought to be proclaimed static (rather than auto) ideally.

The const catchphrase indicates that a variable or item esteem is consistent and can't be changed at the gathering time.

Example:

// simple C program to demonstrate the const specifier
#include <stdio.h>     //here, we have the standard input, and output module //into our program
#include <conio.h>    //here, we have the console input and output module //into our program
int main()
{
	const int num = 5;     //here, we are declaring the constant integer variable //with the value 1
	num = 10;           //here, we are modifying the previously declared value
	return 0;
}

Output:

The above program will throw an error like this:
Error: assignment of the read-only variable ‘num.’

Using enum keyword:

The enum in C is otherwise called the identified sort. It is a client-characterized information type that comprises a whole number of qualities and gives significant names to them. The utilization of an enum in C makes the program straightforward and keeps up with it. The enum is characterized by utilizing the enum watchword.

Coming up next is the method for characterizing the enum in C:

enum flag{integer_const1, integer_const2,.....integter_constN};

In the above statement, we characterize the enum named as a banner containing 'N' number constants. The default worth of integer_const1 is 0, integer_const2 is 1, etc. We can likewise change the default worth of the whole number constants at the hour of the statement.

Specification (or enum) is a client-characterized information type in C and C++. It is mainly used to relegate names to essential constants that make a program simple to peruse and keep up with.

Syntax:

enum enum_name{int_const1, int_const2, int_const3, …. int_constN};

Example:

// simple C program to demonstrate the const specifier
// In C and C++ internally the default
// type of 'var' is int
enum VAS { var = 5 };


// In C++ 11 (can have any integral type):
enum : type { var = 5; }


//were my type = int, char, long, etc.
// but it can't be a float, double, or user-defined data type.

Using constexpr keyword:

The keyword constexpr was presented in C++11 and worked on in C++14. It implies consistent articulation. Like const, it tends to be applied to factors: A compiler blunder is raised when any code endeavors to change the worth. Not at all like const, constexpr can likewise be used for capabilities and class constructors. constexpr shows that the worth, or return esteem, is consistent and, where conceivable, is figured at the aggregate time.

A constexpr essential worth can be utilized any place a const number is required, like in format contentions and cluster statements. Furthermore, when a value is figured at order time rather than run time, it helps your program run quicker and utilize less memory.

Example:

// simple C++ program to demonstrate the const specifier
#include <iostream>     // here; we include the input and output stream into our //program
int main()
{
	int v = 5;   //here, we are declaring the integer variable v with the value 5
	constexpr int k = v;     //here, we are declaring the constexpr integer variable
//and assigning the v variable to it 
	std::cout << k;
	return 0;
}

Output:

The above program will throw an error like this:
Error: the value of ‘v’ is not usable in a constant expression because of the variable ‘var’ in a not regular face. Hence to make it stable, we have to declare the variable ‘var’ with the const keyword.

Using Macros:

The large scale in C language is the piece of code that the full-scale esteem can supplant. The full scale is characterized with the assistance of #define preprocessor order, and the large scale doesn't end with a semicolon(;). Full scale is only a name given to specific qualities or articulations. It focuses on no memory area.

When the compiler experiences the full scale, it replaces the prominent scale name with the large scale esteem. Two macros could never have a similar name.

The linguistic structure of the full scale is displayed in the accompanying figure. Here, we will have three parts:

#define - Preprocessor Directive

PI - Macro Name

3.14 - Macro Value

Types of Macros in C Language

The large scale in C language is arranged in light of the various sorts of values that it replaces.

Objects like Macros in C:

An article like macros in C writing computer programs is the macros that get supplanted by specific qualities or sections of code.

Functions like Macros in C:

Capability like macros is the same as the reaactualpability in C programming. We can pass the contentions with the large-scale name and play out the activities in the code fragment.

There is no checking of contentions in macros, so we can involve it as a benefit to pass different datatypes in the exact macros in the C language.

Example:

// simple c program to demonstrate the problems
// in 'Macros'
#include <stdio.h>    //here, we have the standard input, and output module //into our program
#include <conio.h>    //here, we have the console input and output module //into our program
#define v 5
int main()
{
	printf("Printing the original value of v is %d ", v);
#ifdef v
#undef v
//here, we are redefining the v as 10
#define v 10
#endif
	printf("Printing the value of v: %d", v);
	return 0;
}

Output:

Printing the original value of v is 5
Printing the value of v: 10

Related Topics

Structure Pointer in C

Structure Pointer in C In the C programming language, a structure pointer is defined as a pointer that points to the memory block address that stores a structure. Like C standard...

4 minutes read.

Character Set in C

Introduction Every language has some basic elements which are used to represent information. The English language includes alphabets which together shape a sentence, after which the sentences are used to shape...

3 minutes read.

Compilation Process in C language

What is the Compilation Process?  The compilation is a method whereby the source code is converted into object code. It is achieved with compiler assistance. The compiler tests the source code for syntactic...

3 minutes read.

How to find square root in C Language

Before understanding the square root program in C language, one must know about the square root of a number. A square root is a mathematical term. The square root of a...

5 minutes read.

Malloc function in C

When the user or programmer does not know how much memory space is needed in the application, it a needs dynamic memory allocation during runtime. Dynamic memory allocation helps us to...

4 minutes read.

C Data type

Data Types in C with Examples Data types are used to define the type of data that a variable can store to perform a specific operation.ANSI C provides three types of...

2 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Double Specifier in C

What is a double specifier? The term double denotes the double data type in C. It more accurately depicts floating point numbers. The idea that it has twice the precision of...

3 minutes read.

Star Program in C Language

Star Program in C Star patterns are a sequence of * or any other character used to construct any pattern or any like-square geometric form, triangle, hollow square, pyramid, rhombus, etc.  Many programmers worldwide highly...

4 minutes read.

Round Robin Scheduling in C

Round Robin Scheduling in C Round robin is a CPU (Central Processing Unit) scheduling algorithm designed to share the time systems. It is one of the simplest and easiest scheduling algorithms...

4 minutes read.

Difference between Scope and Lifetime in C

In this article, we will discuss about the key differences between scope and lifetime in C, including their definitions, applications, and how they relate to one another. By the end...

8 minutes read.

C –Structure

C structure is a collection of different types of data that is grouped together. It is used to represent records.Structkeyword is used to create a structure. Each element of a...

1 minute read.

Runtime vs compile time in C

In the C programming language, the often used terms in every step consist of compile time and runtime. The compile time is referred to the source code that will be...

4 minutes read.

Ceil and Floor in C

In arithmetic, a rational number is a number that can be expressed as the quotient p/q of two integers. Where q is zero. The set of rational numbers includes all...

6 minutes read.

#error #pragma in C

#error, #pragma in C #error, also known as the error directive in the C language. It will not allow you to make any compilation fail and immediately issues a statement which...

4 minutes read.

Derived Data Types in C

A variable in a program occupies some space in the computer's memory where some value is stored. Each variable in C has an associated data type. A value to be...

4 minutes read.

#define in C

#define in C In the C programming language, the preprocessor directive acts an important role within which the #define directive is present that is used to define the constant or the...

3 minutes read.

Difference between rand() and srand() function in C

What is the rand()?The rand() means random function. This function is used in C. It generates random numbers in the range of 0 to the RAND_MAX. Suppose we generate a...

3 minutes read.

Difference between while and do-while loop in C

Introduction Both 'While' and 'Do-While' loops in C mostly have a similar concept, and the code of both loops runs for mainly similar purposes. Both loops process the program/code in the...

3 minutes read.

Fee Management System in C

The concept is to split every operation into its very own characteristic. Software is made from all of the capabilities mixed with transfer cases. An example of the capabilities may...

5 minutes read.