Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

C Constants

Constants

To prevent modification of variable values by others or yourself, you can employ the const keyword.

This declares the variable as “constant,” rendering it unchangeable and read-only.

Example

const int myNum = 15;  // myNum will always be 15
myNum = 10;  // error: assignment of read-only variable ‘myNum’ 

It’s advisable to declare a variable as constant when its values are not expected to change.

Example

const int minutesPerHour = 60;
const float PI = 3.14

Notes On Constants

Upon declaring a constant variable, it is mandatory to assign it a value.

Example

Like so:

const int minutesPerHour = 60;

However, this approach will not function:

const int minutesPerHour;
minutesPerHour = 60; // error 

Good Practice

Another aspect of constant variables is that it’s considered good practice to declare them using uppercase letters.

While not obligatory, this practice enhances code readability and is commonplace among C programmers.

Example

const int BIRTHYEAR = 1980