3.3 Constants - Literals - shahzade baujiti

Breaking

Wednesday, April 24, 2019

3.3 Constants - Literals


3.3 Constants - Literals

Constants refer to fixed values in the code that you can't change and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer literals, Floating-Point literals, Strings, Characters and Boolean Values.

Integer literals

An Integer literal can be a decimal, octal, or hexadecimal constant.
A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

Example
45 //decimal
0213 //octal
0x4b //hexadecimal

Floating-point literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.

Example
3.14159
314159E-5L

Boolean literals

There are two Boolean literals and they are part of standard C++ keywords:
A value of true representing true.
? A value of false representing false.
You should not consider the value of true equal to 1 and value of false equal to 0.

Character literals

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').

Escape sequence & Meaning
  There are several character escape sequences which can be used in place of a character constant or within a string.

\a alert (bell)
\b backspace
\f formfeed
\n newline
\r carriage return
\t tab
\v vertical tab
\ backslash
\? question mark
\' quote
\'' double quote
\ooo character specified as an octal number
\xhh character specified in hexadecimal

String literals

String literals are enclosed in double quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.

You can break a long line into multiple lines using string literals and separate them using whitespaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"
"hello, \
dear"
"hello, ""d""ear"

Defining Constants

There are two ways in C++ to define constants:
* Using #define preprocessor.
* Using const keyword.

The #define Preprocessor:
Following is the form to use #define preprocessor to define a constant:
#define identifier value

Example:
#include <iostream>
using namespace std;
#define WIDTH 5
#define LENGTH 10

The const Keyword: You can use const prefix to declare constants with a specific type as follows:
const type variable = value;

Example:
#include&ly;iostream>
using namespace std;
int main()
{
const int LENGTH =10;
const int WIDTH =5;
}




No comments:

Post a Comment