×

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

Call Back Function in Embedded C

Callback function are one the most remarkable systems in C. A callback function is any code that is passed as a contention to another code, so this is the last...

3 minutes read.

What is required in each C Program?

Each C program must require one function, i.e., main() function. It is because when we execute the C program, C compiler looks for the main() function, and from here only...

5 minutes read.

Difference between C and Java

C programming and Java programming are two of the earliest programming languages. C programming follows a procedural approach whereas Java programming follows an object-oriented approach. Java programming is a part...

3 minutes read.

Prime Number code in C

Prime Number Programs in C language In this tutorial, we will learn how to check whether the given number is a prime number or not, and how to print all the...

4 minutes read.

How to Avoid Structure Padding in C

Generally, when an object of some structure type is declared, some contiguous memory will be allocated in block form, which will be allocated to structure members. To understand structure padding...

3 minutes read.

Type Casting in C

Type casting is a way to convert a variable from one data type to another data type.Syntax: (type) expression;     Example: #include <stdio.h> int main() { int a,b; float sum; printf("Example of Type Casting\n"); printf("Enter any integer nos:"); scanf("%d",&a,&b); sum=a+b; printf("Sum: %f",sum); return 0; } Output Example...

1 minute read.

If Statement in C

Decision Control Statements We frequently desire one set of instructions to be carried out in one circumstance while another set of instructions to be carried out in a completely different circumstance....

3 minutes read.

Socket Programming in C

Socket programming is a process that connects the two or more nodes on a networking communication with respective to each other. One of the sockets that determines the socket (I.e.,...

5 minutes read.

How to open a C file on android mobile

A C file is a file that has a .c extension and contains code written in the C language. C is a computer programming language developed by Dennis Ritchie at...

4 minutes read.

C Programming Tutorial

What is C Programming C is most popular and widely used computer programming language. It was developed by Dennis Ritchie in 1972 at the Bell Lab. It is used to develop system application software. There...

8 minutes read.

Calendar application in C

Introduction to the calendar application We all are familiar with the calendar. It plays a crucial role in our daily life. We run toward the calendar whenever we want to know...

6 minutes read.

7 Best IDEs for C/C++ Developers in 2024

As we all know that in programming languages, C is known as the building block which cannot be contradicted, and C++ is the prolong kind of C and it can...

4 minutes read.

Heap Sort in C

In this tutorial, we will learn about heap sorting in C language, but before going to Heap sort, we have to know the concept of Complete Binary Tree. What is Complete...

8 minutes read.

Recursion in C

Recursion is a programming technique that allows the programmer to call the function within the same function. The function which calls the same function is known as recursive function but a...

1 minute read.

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.

2f in C language

Float data type in c: Double-precision floating-point numbers with up to 17 significant digits are stored in the FLOAT data type. FLOAT is equivalent to C's double data type and IEEE...

3 minutes read.

Long int in C

We use data type to avoid the type of data to be stored for a variable at the time of declaration.So, we can say that the variable type is known...

3 minutes read.

How to get ASCII value in C

For text data on computers and the internet, ASCII (American Standard Code for Information Interchange). It is the most widely used character encoding standard. One hundred twenty-eight alphabetic, numeric, special...

3 minutes read.

Flexible Array Members in a Structure in C

There is flexibility to declare array from c99 generation onwards that declaration of the collections can be made possible without even mentioning its dimension, which means that the displays are...

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.