top

Search

C Tutorial

.

UpGrad

C Tutorial

Constants in C

When diving into the world of programming, understanding the basics is crucial to building a strong foundation. In C programming, one of these basic concepts is "constants." 

This article will guide you through the notion of constants in C, their uses, and the different types with comprehensive examples. 

By the end of it, you will have gained a robust understanding of constants in C programming language, equipping you to write more efficient and readable code.

Understanding Constants in C: Definition, Usage and Significance

Constants, as the term suggests, refer to fixed values that do not change during the execution of a program. They are also known as "literals" in C programming. Once defined, constants in C cannot be modified or reassigned, hence offering a level of safety and predictability in your code.

Constants in C play a pivotal role in writing efficient, readable, and safer code. They are commonly used when a value is repeated throughout the program and when it's crucial to prevent accidental modification of the value. 

The role of constants in C is significant as they work on improving the efficiency, readability, and safety of your code. They are often used to define fixed values like the value of PI in mathematics, the number of days in a week, the maximum size of an array, etc.

By now, you must’ve understood what is a constant in C, however, knowing the types of constants in C examples is another imperative aspect of comprehending the right implementation of constants across programs. For instance, integer constants in C are used when the value is a whole number and it doesn't contain any decimal or fractional part. On the other hand, real constants are used when the value has a fractional part, such as the value of PI.

Moreover, having a sound knowledge of primary constants in C, like integer and character constants, along with more complex constants, like enumeration and macro constants, opens up more programming possibilities and gives you more tools to solve problems.

Before delving into the types of constants in C and their examples, let’s learn what are Literals.

What Are Literals In C?

In C programming, literals are the data given in a variable or constant. They are the fixed values that a program processes. Examples of literals are numbers (integer or real), characters ('a', 'b', 'c'), and strings ("abc", "hello").

Types of Constants

There are several types of constants in C. These include: 

  • Integer Constants

  • Real or Floating-Point Constants

  • Character Constants

  • String Constants

  • Enumeration Constants

  • Macro constants. 

Let’s take the subsequent sections to understand these types in more detail, along with well, fleshed out examples and explanations! 

Integer Constants

Integer constants in C refer to a sequence of digits. There are three types of integer constants: decimal (base 10), octal (base 8), and hexadecimal (base 16).

int decimal = 10;    // Decimal constant
int octal = 012;     // Octal constant
int hex = 0xA;       // Hexadecimal constant

Real or Floating Point Constants

Real constant in C comprise numbers that have a fractional part. They can be written in two forms: decimal form and exponential form.

float decimalForm = 12.345;    // Decimal form
float exponentialForm = 1.23e4; // Exponential form

Character Constants

Character constants in C are the single alphabet, digit, or special symbols enclosed within single quotes, like 'a', 'z', '1', '$', etc.

char charA = 'a'; 
char digit1 = '1';
char dollarSign = '$';

String Constants

String constants in C are a sequence of characters enclosed in double-quotes. A string constant in C automatically adds a null character '\0' at the end.

char string[] = "Hello, World!";

Declaration and Initialization of Constants

Syntax of Declaring Constants

In C, we declare a constant using the const keyword followed by the data type and then the constant's name.

const data_type constant_name;

Examples of Declaring Constants

Here are some examples of declaring constants in C:

const int LENGTH = 10;
const char GRADE = 'A';
const float PI = 3.14159;

Syntax of Initializing Constants

In C, constants can also be initialized using the #define preprocessor directive.

#define constant_name value

Examples of Initializing Constants

Here are some examples of initializing constants in C:

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

Enumeration Constants

Enumeration constants (also known as an "enum") in C is a user-defined data type that consists of integral constants. To define enums, we use the keyword enum.

Definition of Enumeration Constants

Enumeration constants in C is a way of creating an integral constant with a meaningful name.

Syntax of Enumeration Constants

Here's the syntax for enumeration constants:

enum enum_name { const1, const2, ..., constn } var_name;

Examples of Enumeration Constants

enum boolean { false, true } isTrue;

In this example, false is equivalent to 0, and true is equivalent to 1.

Macro Constants

Macro constants in C are values that are defined using #define directive. These values cannot be changed during the program execution.

Definition of Macro Constants

Macro constants are named constants. Instead of using const keyword, we use #define preprocessor to define a constant.

Syntax of Macro Constants

Here's the syntax for macro constants:

#define identifier value

Examples of Macro Constants

#define PI 3.14
#define MAX_SIZE 100

In this example, we’ve defined two macro constants in C - one is by the name PI, and the other is by the name MAX_SIZE. 

Advantages of Using Constants

Using constants in C programming comes with a myriad of benefits that can significantly improve your code's efficiency, readability, and maintainability. Below we'll explore these advantages in greater detail:

Code Readability

By employing constants in your programs, you make your code more understandable. For instance, instead of hardcoding a value like 3.14 throughout your program, you could define a constant PI. Now, whenever PI is referenced, it's immediately clear to any programmer what that value represents. This increase in readability makes it easier for others (and your future self) to understand your code, thereby enhancing its maintainability.

Preventing Accidental Modification of Values

The core attribute of a constant is that its value cannot change. This inherent immutability safeguards critical values in your program. If a particular value needs to stay the same throughout your program's execution (like the value of PI), defining it as a constant will prevent any accidental modifications, leading to fewer bugs and unexpected behaviours.

Optimising Memory Usage

Constants don't occupy memory in the way variables do. For instance, when you define an integer constant, the C compiler does not allocate memory space for it, unlike an integer variable. Instead, the compiler replaces instances of the constant in your code with its value during compilation. This memory optimisation can be particularly beneficial in memory-constrained environments like embedded systems.

Standardizing Values Across Files

If you're working on a large project with multiple source files, using constants can help standardise certain values across these files. You can define constants in a header file and include that header in any source file that needs those constants. This practice ensures that the same values are used across the entire project, promoting consistency and reducing potential errors.

Easier Code Updates

If you need to change the value of a constant (for example, if you used a constant for the maximum number of students allowed in a class and that number has changed), you only need to change it in one place. Once the constant is updated, all references to it throughout the program will automatically use the new value. This is significantly easier and safer than updating the value everywhere it's used in your code.

Utilising constants in C is a powerful practice that can improve your programs in numerous ways. As you continue to explore C programming, you'll likely find even more situations where constants can be beneficial

Constructing Constants in C: Rules to Follow

As you work with constants in C, it's essential to understand how to construct them properly. There are specific rules for constructing different types of constants: integer constants, real constants or floating-point constants, character constants, string constants, and backslash character constants.

Integer Constants

An integer constant in C programming is a sequence of digits. In order to construct integer constants, there are certain rules users must comply with. These include:

  • The integer constant should at least contain one digit.

  • An integer constant can be positive/negative. In case the integer constant is preceded by no sign, the integer is accepted as a positive.

  • There is no comma or blank within an integer constant.

  • The integer constant should not have a decimal point.

  • -2147483648 to 2147483647 is the acceptable range in C for integer constants.

Real Constants / Floating Point Constants

Real constants, also referred to as floating-point constants, are numbers that have a fractional part. They can be implemented in two forms: decimal form and exponential form. The rules for constructing real constants are:

  • A real constant should hold at least 1 digit.

  • Real constants should comprise a decimal point, which could be before, after, or between the digits.

  • Real constants can either be positive or negative. However, in case there is no sign that precedes the real constant, the constant is assumed to be positive.

  • The default sign of the fractional part or exponent is positive.

String and Character Constants

String and character constants have their own construction rules:

  • Character constant is a single character enclosed in single quotes, like 'a', 'Z', '5', etc.

  • A string constant is a sequence of characters enclosed in double-quotes. It could include letters, digits, special characters, and white spaces, like "Hello", "2023", "C Programming", etc.

  • C automatically appends a null character ('\0') to all the string constants.

  • The maximum character string length is 8192 characters.

Backslash Character Constants

Backslash character constants are escape sequences that represent special characters. Some backslash character constants are:

  • '\n': Newline

  • '\t': Horizontal tab

  • '\b': Backspace

  • '\r': Carriage return

  • '\f': Form feed

  • '\v': Vertical tab

  • '\a': Alert or bell

  • '\': Backslash

  • '?': Question mark

  • ''': Single quote

  • '"': Double quote

Each of these backslash character constants represents a single character constant and can be used wherever a character constant is required.

Following these rules for constructing constants helps to ensure your C programs are syntactically correct, enhancing the program's efficiency and readability.

Creation and Use of Constants in C

Use of The ‘Const’ Keyword

The const keyword is used in C to declare a constant. This keyword ensures that the variable's value declared using const cannot be changed.

const int LENGTH = 10;

In this example, LENGTH is declared as a constant integer with a value of 10.

Use of The ‘#Define’ Preprocessor

The #define preprocessor is another way of declaring a constant in C

#define LENGTH 10

In this example, LENGTH is defined as a constant with a value of 10.

Practice Problems On Constants In C

After learning the theory, let's put your knowledge into practice. Here are some problems for you to solve.

1. Problem: Write a C program to calculate the circumference of a circle using a constant PI.
Hint: The formula for the circumference of a circle is 2PIr, where r is the radius of the circle. Declare PI as a constant using #define or const.

2. Problem: Write a C program to create an enumeration constant for the days of the week and print them.
Hint: Use enum keyword to create an enumeration for days of the week. In a loop, print each day.

3. Problem: Write a C program that defines the months of a year as macro constants and prints them.
Hint: Use the #define directive to declare each month as a macro constant. To print, simply use the printf function with the defined constants.

4. Problem: Write a C program that defines constants for a student's name, roll number, and grade they received in a subject. Print these details.
Hint: You can use the const keyword to declare the name and roll number as character constants and grade as an integer constant.

5. Problem: Write a C program that uses a constant integer to define the size of an array. Fill this array with the first n natural numbers and print them.
Hint: Use a constant integer to declare the size of an array. Use a loop to fill and another loop to print the array elements.

Remember, practice is the key to mastering any concept. Happy coding!

Conclusion

Constants in C, though seemingly simple, are critical building blocks in writing efficient and easy-to-understand code. As we've explored, there are various types of constants, each with its unique usage and benefits. They not only make your code safer and more readable but also contribute significantly to memory optimisation.

To unlock more power in C programming and dive deeper into its concepts, check out upGrad’s Master of Science in Computer Science Program,  offered under Liverpool John Moores University. Not only will you gain practical knowledge, but you'll also earn an industry-recognised degree to boost your career. 

Start your journey with upGrad today!

FAQs

1. What are constants in C?

Constants in C are fixed values that do not change during the execution of a program.

2. What are the different types of constants in C?

There are several types of constants in C: integer constants, real or floating-point constants, character constants, string constants, enumeration constants, and macro constants.

3. How do I declare and initialise a constant in C?

Constants in C can be declared using the const keyword or initialised using the #define preprocessor directive.

4. What are the advantages of using constants in C?

Using constants in C improves code readability, prevents accidental modification of values, and reduces memory usage.

5. What are enumeration constants in C?

Enumeration constants (also known as an "enum") in C is a user-defined data type that consists of integral constants.

Leave a Reply

Your email address will not be published. Required fields are marked *