Search Result
Details here...

C Variables, Constants and Literals

Previous

Data Type in C | Basics

Next

Escape Sequences in C


Variables are the storage locations designated by some name for storing data.

In C programming language, a variable is declared using the keywords int, float, char, etc., and giving certain identifiers as name, as discussed in previous lesson Keywords and Identifiers. Then the variable can be assigned any constant value or other variables.
int age = 10;

Explanation

In the above code, we define a variable identified as age of type int and assign it the value 10. Which means, the variable age has the value 10, which is an integer. So, the variable age can store only integer values.

In the similar way, we can define a variable of type float, char, double, etc.
float salary = 2800;
char favouriteLetter = 'D';
double pi = 3.141592653589793;

Did you notice?

It is compulsory to use single quotes (') to define a character variable.

Variables are the identifiers

Variables are the identifiers for values, hence, they should be named following the sets of rules to name identifiers, which we discussed in the earlier chapters.

Constants

Constants are the variables which are declared with the keyword const. Constants are used to define the values which are not meant to be changed.

For example; we can define a constant variable PI of type double and assign it the value 3.141592653589793.
const double PI = 3.141592653589793;
We can also define a constant variable using macros. We will discuss macros in the coming chapters.

Literals

Literals are the values which are directly assigned to the variables. They are values themselves, which are not variables.

In the above examples, 3.141592653589793, 2800, 'D', are literals, which is not a variables.

Some of the literals are defined in the C language itself. For example, NULL is a literal, which is defined as NULL in C language.

Integers, floating point numbers, characters, strings, etc. are all literals.

  • Integer is a literal that represents a number, without any fractional or exponential part, in decimal, octal, or hexadecimal system.
    Examples:
    10, 022, 0x10, etc.
  • Floating point number is a literal that represents a number with fractional or exponential part.
    Examples:
    10.5, 0.5e2, 0.5e-2, etc.
  • Character is a literal that represents a single character. Example; 'D' is a character literal.
    Examples:
    'D', 'd', 'a', etc.
  • String is a literal that represents a sequence of characters. Example; "Hello World" is a string literal.
    Examples:
    "Hello World", "Hello\n", "World\n", etc.
    In the above example, \n is a new line character. It is used to represent a new line in a string.

Info

We will learn about the new line character (\n), under the escape sequence in the next chapter.

By darpan.kattel
Previous

Data Type in C | Basics

Next

Escape Sequences in C