Constant and Literals


Constant and Literals

Constants are fixed values that the programme cannot change while it is running. Literals are another name for these fixed values. Integer constants, character constants, floating constants, and string literals are all examples of basic data types. There are also enumeration constants. Constants are processed similarly to ordinary variables, with the exception that their values cannot be changed after they have been defined.

Integer Literals

A decimal, octal, or hexadecimal constant can be used as an integer literal. The base or radix of a number is specified by a prefix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. A suffix that is a mix of U and L, for unsigned and long, can be added to an integer literal. The suffix can be capitalised or capitalised, and it can appear in any sequence.

#include<stdio.h> #include<conio.h> void main() { const int i=15; /* constant int literal */ printf("integer literal: %d",i); getch(); }

output:

integer literal: 15

Floating-point Literals

An integer portion, a decimal point, a fractional part, and an exponent part make up a floating-point literal. Floating point literals can be represented in decimal or exponential form. You must include the decimal point, the exponent, or both when representing decimal form, and you must include the integer portion, the fractional part, or both when representing exponential form. e or E introduces the signed exponent.

#include<stdio.h> #include<conio.h> void main() { const float a=3.5; /* constant float literal */ const float b=2.5; /* constant float literal */ float sum; sum=a+b; printf("sum: %f",sum); getch(); }

output:

sum: 6.0

Character Constants literal

Single quotes are used to surround character literals, so 'x' can be kept in a simple char variable. Certain letters in C, such as newline (\n) and tab (\t), have unique significance when preceded by a backslash.

#include<stdio.h> #include<conio.h> void main() { const char i='ms'; /* constant character literal */ printf("%c",i); getch(); }

output:

ms

String Literals

Double quotes "" are used to surround string literals or constants. Plain characters, escape sequences, and universal characters are among the characters in a string that are similar to character literals. String literals can be used to split a large line into many lines and white spaces can be used to separate them.

#include<stdio.h> #include<conio.h> void main() { const char str[] = "Knowledge 2Life"; /* constant string literal */ printf("%s",str); getch(); }

output:

Knowledge 2Life

Defining Constants

There are two simple ways to define constants in C.

  • The keyword const is used.
  • Using the #define pre-processor.
#include<stdio.h> #include<conio.h> void main() { const float pi=3.14; /* constant value */ printf("pi is: %f",pi); getch(); }

output:

pi is: 3.140000