0% found this document useful (0 votes)
35 views19 pages

Constants Literals

Uploaded by

Thomas Graham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views19 pages

Constants Literals

Uploaded by

Thomas Graham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Bachelor of Information Technology

PRG1002 - Programming I

Constants/Literals
in C++

Expressions with fixed values


Contents

● What is a Literal?

● The #define preprocessor

● The const keyword


What is a Literal?

● Literal is a fixed value that is written directly into the source code. Literals are compiled into
constants with the values in the source code.

int x = 5;
cout << "Hello world!" << endl;

● In the above example, Hello world! and 5 are literals.

● Both literals and variables have a value, and they both have a type.
○ The type of a variable is given in its declaration.
○ The type of a literal is assumed from the value and format of the literal itself.
Types of Literals

● Literals can be of any primitive (built-in) data type:


○ Integer
○ Floating-point (includes float and double)
○ Character
○ String
○ Boolean
Integer Literals

● Integer literals represent integer values,


int decimalBase = 123;
and we can use special syntax to indicate
// the value will be shown in decimal base
integers of different bases or number
cout << decimalBase << endl; // 123
systems
○ Octal literals begin with 0 int octalBase = 0123;
○ Hexadecimal literals begin with 0x // the value will be shown in octal base
○ Binary literals begin with 0b cout << octalBase << endl; // 83

int hexbase = 0x12;


// the value will be shown in octal base
cout << hexBase << endl; // 18

int binaryBase = 0b110;


// the value will be shown in octal base
cout << binaryBase << endl; // 6
Integer Literals

● We can also specify an integer literal type long and unsigned. We can change the type of an integer
literal by adding a suffix as shown below:

unsigned unValue = 120U;


long longValue = 1000L;
cout << unValue << endl; // 120
cout << longValue << endl; // 1000
Floating-point Literal

● A floating-point literal can be represented in either decimal form or exponential form.

● Examples of decimal form:


○ 1.314 float decValue = 0.00134;
○ 67.2f // the value will be shown with decimal point
○ 45.678123L cout << decValue << endl; // 0.00134

● Examples of exponential form:


float expValue = 1.34E-3;
○ 3e10
// the value will be shown with decimal point
○ 1.3e-4 cout << expValue << endl; // 0.00134
Floating-point literal

● Add the f(F) suffix to declare a float literal:

float decValue = 0.00134f;

● Add the l(L) suffix to declare a long literal:

float decValue = 0.00134l;

● With no suffix, the default data type of a floating-point literal is double.


Character Literal

● Character literals are sequence of characters


char c = 'a';
that are enclosed by single quotes. These literals
std::cout << "char: " << c << std::endl;
are used to represent characters.
// a

● If the character literal is a plain character (e.g.,


wchar_t lc = L'a';
‘x’), an escape sequence (e.g., ‘\t’), or a utf-8
std::cout << "wide char: " << lc << std::endl;
character value, it can be stored in a variable of // 97
char type.
char u8c = u8'a';
● UTF-16, and wide character sequences require std::cout << "utf-8: " << u8c << std::endl;
larger data types (wchar_t and char16_t) // a

● If you want to store multiple characters then we char16_t uc = u'a';


have to use character array or strings. We will std::cout << "utf-16: " << uc << std::endl;
discuss the arrays and strings later in the // 97
upcoming weeks.
Character Literal

● There are some special characters that are used for different purpose in character literals.

Description Escape Code

New line \n Description Escape Code

Horizontal tab \t Double Quote (“) \”

Vertical tab \v Question mark (?) \?

Backspace \b Backslash (\) \\

Alert (beep) \a Null character \0

Single Quote (‘) \‘


String Literal

● String literals are enclosed by double quotes (“ ”).

"Hello, this is a string literal\n";

● We can use the same special characters in string literals as we can in character literals.

● So far we’ve only used these to print output to the console, but we will learn more about strings in
another lesson.
Boolean Literal

● Boolean literals are used with the bool data type. For a boolean literal there are two possible values:
true and false.

bool isTrue = true;


bool isFalse = false;

cout << "True will be displayed as " << isTrue << endl;
cout << "True will be displayed as " << isFalse << endl;

● cout displays true as 1 and false as 0.

● Use the boolalpha output modifier to print ‘true’ and ‘false’ instead
bool isTrue = true;
bool isFalse = false;
cout << boolalpha;
cout << "True will be displayed as " << isTrue << endl;
cout << "True will be displayed as " << isFalse << endl;
Constants
Defining constants

● Constants are treated just like regular variables except that their values cannot be modified after their
definition.

● Use a constant variable to avoid accidentally changing a variable that should not change.

● There are two simple ways in C++ to define constants:


○ Using const keyword.
○ Using #define preprocessor
Using const keyword

● We can use const prefix to declare constants with a specific data type.

● The syntax for creating a constant variable is,

const type variableName = value;

● The constant variables should be initialized with value when the variable is created.

const double PI = 3.141592653589793238;

● If we try to change the value of the constant variable after it’s initialization, we will get an error

// can't do this
PI = 231.424; // this line will result in compile error
Using #define preprocessor

● Another mechanism to name constant values is to use the #define preprocessor directive.

● The syntax of the preprocessor directive is,

#define identifier replacementValue

● After this directive, any occurence of identifier in the code is interpreted as


replacementValue, where replacementValue is any sequence of characters (until the end of the
line).
#define PI 3.141592653589793238

● This is a blind replacement as it is performed by the preprocessor, and happens before the program is
compiled. The validity of the types or syntax involved will not be checked in any way.
Using #define preprocessor

#include <iostream>
using namespace std;
● Note that #define lines are preprocessor
#define PI 3.141592653589793238
directives, and they do not require semicolons
at the end (;) int main()
{
double r = 5.0;
● If a semicolon is included in the line, it is part double areaOfCircle;
of replacement sequence and is also included // Area of Circle: PI
areaOfCircle = r * r * PI;
in all replaced occurrences.
cout << areaOfCircle << endl;

return 0;
}
Summary

● Literal is a notation for representing a fixed value in source code.

● An integer literal can be decimal, octal, binary, or hexadecimal constant. It can also have a suffix that is
a combination of U and L, for unsigned and long respectively.

● A floating-point literal can be expressed as a decimal or an exponential value. By default floating-point


values are declared as double types, unless a suffix is provided.

● Character literal is enclosed in single quotes and string literal is enclosed in double quotes.

● Boolean literal can be true or false, the value of true will be 1 and false will be 0.

● Constants can be of any of the basic data types and can be declared as const variables, or with the
#define preprocessor directive.
References

Tutorialspointcom. 2019. Wwwtutorialspointcom. [Online]. [19 July 2019]. Available from:


https://www.tutorialspoint.com/cplusplus/cpp_constants_literals

Tutorialcupcom. 2019. Tutorialcupcom. [Online]. [19 July 2019]. Available from:


https://www.tutorialcup.com/cplusplus/constants-and-literals.htm

Cpluspluscom. 2019. Cpluspluscom. [Online]. [19 July 2019]. Available from:


http://www.cplusplus.com/doc/tutorial/constants/

You might also like