Initialization of Variables

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

LECTURE 11.

INITIALIZATION OF VARIABLES

When declaring a regular local variable, its value is by default undetermined. But you may want
a variable to store a concrete value at the same moment that it is declared. In order to do that,
you can initialize the variable. There are two ways to do this in C++:

The first one, known as c-like, is done by appending an equal sign followed by the value to
which the variable will be initialized:

type identifier = initial_value ;

For example, if we want to declare an int variable called a initialized with a value of 0 at the
moment in which it is declared, we could write:

int a = 0;

The other way to initialize variables, known as constructor initialization, is done by


enclosing the initial value between parentheses (()):

type identifier (initial_value) ;

For example:

int a (0);

Both ways of initializing variables are valid and equivalent in C++.

// initialization of variables 6
#include <iostream>
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value
undetermine
d
a = a + 3;
result = a b;
cout << result;
return 0;
}

Introduction to strings

Variables that can store non-numerical values that are longer than one single character are known
as strings.

The C++ language library provides support for strings through the standard string
class. This is not a fundamental type, but it behaves in a similar way as fundamental
types do in its most basic usage.
A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type we need to include an additional header file in our source code: <string>
and have access to the std namespace (which we already had in all our previous programs thanks
to the using namespace statement).

// my first string This is a string


#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}

As you may see in the previous example, strings can be initialized with any valid string literal
just like numerical type variables can be initialized to any valid numerical literal. Both
initialization formats are valid with strings:

string mystring = "This is a string";


string mystring ("This is a string");

Strings can also perform all the other basic operations that fundamental data types can, like being
declared without an initial value and being assigned values during execution:

// my first string This is the initial string content


#include <iostream> This is a different string content
#include <string>
using namespace std;
int main ()
{
string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;
mystring = "This is a different string content";
cout << mystring << endl;
return 0;
}

For more details on C++ strings, you can have a look at the string class reference.

Constants
Constants are expressions with a fixed value.

Literals

Literals are used to express particular values within the source code of a program. We have
already used these previously to give concrete values to variables or to express messages we
wanted our programs to print out, for example, when we wrote:
a = 5;

the 5 in this piece of code was a literal constant.

Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters,


Strings and Boolean Values.

Integer Numerals
1776
707
273

They are numerical constants that identify integer decimal values. Notice that to express a
numerical constant we do not have to write quotes (") nor any special character. There is no
doubt that it is a constant: whenever we write 1776 in a program, we will be referring to the
value 1776.

In addition to decimal numbers (those that all of us are used to use every day) C++ allows the
use as literal constants of octal numbers (base 8) and hexadecimal numbers (base 16). If we want
to express an octal number we have to precede it with a 0 (zero character). And in order to
express a hexadecimal number we have to precede it with the characters 0x (zero, x). For
example, the following literal constants are all equivalent to each other:

75 // decimal
0113 // octal
hexadecim
0x4b // al

All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral,
octal numeral and hexadecimal numeral, respectively.

Literal constants, like variables, are considered to have a specific data type. By default, integer
literals are of type int. However, we can force them to either be unsigned by appending the u
character to it, or long by appending l:

75 // int
75u // unsigned int
75l // long
75ul // unsigned long

In both cases, the suffix can be specified using either upper or lowercase letters.

Floating Point Numbers


They express numbers with decimals and/or exponents. They can include either a decimal
point, an e character (that expresses "by ten at the Xth height", where X is an integer value
that follows the e character), or both a decimal point and an e characte

3.14159 // 3.14159
6.02e23 // 6.02 x 10^23
1.6e19 // 1.6 x 10^19
3.0 // 3.0
These are four valid numbers with decimals expressed in C++. The first number is PI, the
second one is the number of Avogadro, the third is the electric charge of an electron (an
extremely small number) -all of them approximated- and the last one is the number three
expressed as a floating-point numeric literal.

The default type for floating point literals is double. If you explicitly want to express a float
or long double numerical literal, you can use the f or l suffixes respectively:

3.14159L // long double


6.02e23f // float

Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be written
using either lower or uppercase letters without any difference in their meanings.

Character and string literals


There also exist non-numerical constants, like:

'z'
'p'
"Hello world"
"How do you do?"

The first two expressions represent single character constants, and the following two represent
string literals composed of several characters. Notice that to represent a single character we
enclose it between single quotes (') and to express a string (which generally consists of more
than one character) we enclose it between double quotes (").

When writing both single character and string literals, it is necessary to put the quotation marks
surrounding them to distinguish them from possible variable identifiers or reserved keywords.
Notice the difference between these two expressions:

x
'x'

x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single
quotation marks) would refer to the character constant 'x'.

Character and string literals have certain peculiarities, like the escape codes. These are special
characters that are difficult or impossible to express otherwise in the source code of a program,
like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of
some of such escape codes:
n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)

For example:

'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree"

Additionally, you can express any character by its numerical ASCII code by writing a backslash character (\)
followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16) number. In the first case
(octal) the digits must immediately follow the backslash (for example \23 or \40), in the second case
(hexadecimal), an x character must be written before the digits themselves (for example \x20 or \x4A).

String literals can extend to more than a single line of code by putting a backslash sign (\) at the end of
each unfinished line.

"string expressed in \
two lines"

You can also concatenate several string constants separating them by one or several blank spaces,
tabulators, newline or any other valid blank character:

"this forms" "a single" "string" "of characters"

Finally, if we want the string literal to be explicitly made of wide characters (wchar_t), instead of narrow
characters (char), we can precede the constant with the L prefix:

L"This is a wide character string"

Wide characters are used mainly to represent non-English or exotic character sets.

Boolean literals
There are only two valid Boolean values: true and false. These can be expressed in C++ as values of type bool by
using the Boolean literals true and fals

You might also like