0% found this document useful (0 votes)
120 views17 pages

Variables and Constants: Study Guide For Module No. 3

This document provides a study guide for a module on variables and constants in C++. It discusses the key concepts of variables, constants, and identifiers. The main points are: - Variables and constants provide named locations to store and manipulate data in a computer's memory. - Identifiers are the descriptive names given to variables and constants. They must follow specific naming rules and conventions to be valid. - Common conventions for identifier names include lowercase for single word names and "snake_case" or "CamelCase" for multi-word names. Names should be meaningful and avoid abbreviations.

Uploaded by

Ji Young
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)
120 views17 pages

Variables and Constants: Study Guide For Module No. 3

This document provides a study guide for a module on variables and constants in C++. It discusses the key concepts of variables, constants, and identifiers. The main points are: - Variables and constants provide named locations to store and manipulate data in a computer's memory. - Identifiers are the descriptive names given to variables and constants. They must follow specific naming rules and conventions to be valid. - Common conventions for identifier names include lowercase for single word names and "snake_case" or "CamelCase" for multi-word names. Names should be meaningful and avoid abbreviations.

Uploaded by

Ji Young
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/ 17

FM-AA-CIA-15 Rev.

0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

STUDY GUIDE FOR MODULE NO. 3

VARIABLES AND CONSTANTS


MODULE OVERVIEW

Welcome to this module! By the time that you are reading this, you already know the basic C++ program
structure and have written and build your first C++ program. Further, the importance of documenting your
program by including comments was also discussed to you in the previous module. In order to expand your
knowledge in writing programs that perform useful tasks that really save you work, we introduce the concept of
variables and named constants.

MODULE LEARNING OBJECTIVES

By the end of this module you should be able to:


 Distinguish among a variable, a named constant, and a literal constant
 Explain how data is stored in memory
 Select an appropriate name, data type, and initial value for a memory location
 Declare a memory location in C++
 Use an assignment statement to assign data to a variable
 Use variables in your C++ program
 Determine the scope and lifetime of a variable in a C++ program

LEARNING CONTENTS (Identifiers and Keywords)

Introduction

Programming involves the manipulation and processing of data. Thus, there has to be a way for the programmer
to store this data in the computer memory. The computer memory is composed of memory locations, with each
memory location having a unique numeric address. However, rather than using a cryptic numeric address, a
programmer uses descriptive words that are easier to remember to refer to a memory location. Every memory
location that a programmer uses in his program must be declared using a C++ instruction that assigns a name,
a data type, and (optionally) an initial value to the location. There are two types of memory locations that a
programmer can declare: variable and named constants. In this unit, you will learn about identifiers and how to
select a name for a memory location. Also you will learn about keywords (reserved words in C++ programming
that are part of the syntax).

1.1 Identifiers

Every memory location that a programmer uses in the program must be assigned a name. The name, also
called the identifier, should describe the meaning of the value stored therein. An identifier is a descriptive name
to a variable and named constant that the program will use and should help you remember the purpose of the
memory location. However, there are specific rules that a programmer must follow in declaring identifiers in C++
programs. A valid identifier must follow the following rules:

 A memory location’s name must begin with a letter and it can include only letters, numbers, and
underscore (_)
 No punctuation characters or spaces are allowed in a memory location’s name
 The C++ compiler you are using determines the maximum number of characters in a name.
 The name also cannot be the same as the keyword because keyword has a special meaning in a
programming language.

PANGASINAN STATE UNIVERSITY 1


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

Note – The C++ language is a "case sensitive" language. That means that an identifier written in capital letters
is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT
variable is not the same as the result variable or the Result variable. These are three different identifiers
identifying three different variables.

You can choose any name as an identifier if you follow the above rules. However, you should give meaningful
names to the identifier that makes sense.

Examples of identifiers:

LEARNING ACTIVITY 1

Explain why the identifiers given on the table above were considered as invalid, bad, and good identifiers.

LEARNING CONTENTS (Identifiers)

1.1.1 Identifier naming conventions


Programmers often follow naming conventions for variables and named constants to make their programs easy
to read and maintain.
In C++ it is a convention that variable names should begin with a lowercase letter. If the variable name is one
word, the whole thing should be written in lowercase. Let’s take a look at the following variable declarations:
1 int value; // correct
2
3 int Value; // incorrect (should start with lower case letter)
4 int VALUE; // incorrect (should start with lower case letter)
5 int VaLuE; // incorrect (see your psychiatrist) ;)

However, for a variable or function name which is multi-word, there are two common conventions:

1. words separated by underscores, called snake_case


2. intercapped (sometimes called camelCase, since the capital letters stick up like the humps on a camel).

Let’s look at the following examples of correct and invalid variable declarations for multi-word variables:

1 int my_variable_name; // correct (separated by underscores/snake_case)


2 int my_function_name(); // correct (separated by underscores/snake_case)
3
4 int myVariableName; // correct (intercapped/CamelCase)
5 int myFunctionName(); // correct (intercapped/CamelCase)
6
7 int my variable name; // invalid (whitespace not allowed)

PANGASINAN STATE UNIVERSITY 2


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

8 int my function name(); // invalid (whitespace not allowed)


9
10 int MyVariableName; // valid but incorrect (should start with lower case letter)
11 int MyFunctionName(); // valid but incorrect (should start with lower case letter)

You can follow either conventions for multi-word identifier names. It is common for programmers to use either
and sometimes they use a mix of these two.

Note – C++ standard library uses the underscore or snake_case method for both variables and functions. You’ll see examples of these
in Section 1.2.

1.1.2 Best practices in naming identifiers

1. When working in an existing program, use the conventions of that program (even if they don’t conform
to modern best practices). However, if you are writing new programs, use modern best practices.
2. Avoid naming your identifiers starting with an underscore since these names are usually reserved for
OS, library, and/or compiler use.
3. Make sure that your identifiers clearly state what value they are holding. This would make other
programmers and non-programmers figure out as quickly as possible what your code does.
4. The length of the identifier must be proportional to how widely it is used.
 An identifier with a trivial use can have a short name (e.g. such as i)
 An identifier that is used more broadly (e.g. a function that is called from many different places in a
program) should have longer and more descriptive name (e.g. instead of open, try openFileOnDisk)

The table below shows examples of identifiers that may or may not follow the identifier naming practices
enumerated above.

int ccount Bad What does the c before “count” stand for?
int customerCount Good Clear what we’re counting
int i Either Okay if use is trivial, bad otherwise
int index Either Okay if obvious what we’re indexing
Okay if there’s only one thing being scored,
int totalScore Either
otherwise too ambiguous
int _count Bad Do not start names with underscore
int count Either Okay if obvious what we’re counting
int data Bad What kind of data?
int time Bad Is this in seconds, minutes, or hours?
int minutesElapsed Good Descriptive
int value1, value2 Either Can be hard to differentiate between the two
int numApples Good Descriptive
int monstersKilled Good Descriptive
int x, y Either Okay if use is trivial, bad otherwise

5. In any case, avoid abbreviations. Use your editor’s auto-complete feature if you want to write code
faster. Although using abbreviations reduce the time you need to write your code, they make your code
harder to read. Code is read more often than it is written, the time you saved while writing the code is
time that every reader, including the future you, wastes when reading it.

PANGASINAN STATE UNIVERSITY 3


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

6. Finally, a clarifying comment can go a long way. As what have been discussed in the previous module,
comments make your code easy to understand.

For example, say we’ve declared a variable named numberOfChars that is supposed to store the
number of characters in a piece of text. Does the text “Hello World!” have 10, 11, or 12 characters? It
depends on whether we’re including whitespace or punctuation. Rather than naming the
variable numberOfCharsIncludingWhitespaceAndPunctuation, which is rather lengthy, a well-placed
comment on the declaration line should help the user figure it out:

1 /* holds number of chars in a piece of text -- including whitespace and


2 punctuation!*/
3 int numberOfChars;

LEARNING ACTIVITY 2

Based on how you should name a variable, indicate whether each variable name is correct (follows
convention), incorrect (does not follow convention), or invalid (will not compile), and why.

1. int total; //assume it’s obvious what we are adding


2. int _price;
3. int RESULT;
4. int my identifier;
5. int totalPrice;
6. int 1list;
7. int my_list;
8. int MyList;
9. int REsulT;
10. int product;

LEARNING CONTENTS (Keywords)

Each line of a C++ program is composed of several words. The compiler classifies these words into different
categories: reserved words, standard identifiers, and user-defined identifiers. Section 1.1 focused on the
discussion of user-defined identifiers. In this section, we will discuss the other two categories.

A Reserved word is a word with predefined meaning in C++ and cannot be changed. It is always written in
lowercase letters and can only be used for the purpose, which has been defined to it by the C++ compiler. You
have already came across some of the reserved words in the previous modules. For example,

int value;

Here, int is a reserved word that indicates value is a variable of integer type.

A Standard identifier also have a special meaning in C++. They are the names of the operations defined in
the standard C++ library.

Examples: cin and cout are identifiers of the standard input and output streams

Unlike reserve words, standard identifiers can have their meanings changed by the programmer for other
purposes. However, this is NOT recommended

Both reserved words and standard identifiers have special meanings to the compiler and they are commonly
referred to as keywords.

Keywords are predefined words that have special meanings to the compiler. They refer to both reserved words

PANGASINAN STATE UNIVERSITY 4


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

and library identifiers.

C++ reserves a set of 84 reserved words (as of C++17) for its own use. Here is a list of all the C++ keywords
(through C++17):

The keywords marked (C++11) were added in C++11. If your compiler is not C++11 compliant (or does have
C++11 functionality, but it’s turned off by default), these keywords may not be functional.

C++11 also adds two special identifiers: override and final. These have a specific meaning when used in certain
contexts but are not reserved.

Along with a set of operators, these keywords and special identifiers define the entire language of C++
(preprocessor commands excluded). Because keywords and special identifiers have special meaning, your
IDEs will likely change the text color of these words (often to blue) to make them stand out from other identifiers.

LEARNING ACTIVITY 3

List down the identifiers of the following C++ statements and indicate whether the identifier is a user-defined,
a reserved word, or a standard identifier.

1. int total;
2. cout << sum;
3. float totalPrice;
4. cin >> age;
5. return 0;

LEARNING CONTENTS (Data Types)

PANGASINAN STATE UNIVERSITY 5


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

Introduction

We recall that every memory location that a programmer uses in his program must be declared using a C++
instruction that assigns a name, a data type, and (optionally) an initial value to the location. We’ve already
covered the assignment of name or identifier to the memory location. In this section, we will learn about the
types of data a memory location can store.

In C++, a data type (more commonly just called a type) are declarations for variables. This determines the type
and size of data associated with variables. For example,
int age;
In the above example, our variable age was given type int, which means variable age will represent an integer
value. This means that the variable can only store integers or whole numbers of either 2 or 4 bytes.

C++ fundamental data types are basic types implemented directly by the language that represent the basic
storage units supported natively by most systems. The table below shows these fundamental data types, their
meaning, and their sizes (in bytes):

Data Type Meaning Size (in Bytes)


int Integer 2 or 4
float Floating-point 4
double Double Floating-point 8
char Character 1
wchar_t Wide Character 2
bool Boolean 1
void Empty 0

2.1 C++ int


The int keyword is used to indicate integers. This is used to represent a data type that stores whole numbers.
The size of an integer type of data is usually 4 bytes. This means that it can store values from - 2147483648
to 214748647.

Example: int salary = 24000;

Here, salary is a variable of type int and holds an initial value of 24000.

Rules that must be observed when using integers are:


 Plus (+) signs do not have to be written before a positive integer, although they may be.
 Minus (-) signs must be written when using a negative number
 Decimal points cannot be used when writing integers. Although 14 and 14.0 have the same value, 14.0
is not of type int
 Commas cannot be used when writing integers; hence 2,176 is not allowed; it must be written as 2176
 Leading zeros should be avoided. If you use leading zeros, the compiler will interpret the number as an
octal (base 8) number.

2.2 C++ float and double


The float and double data types are used to store floating-point numbers or real numbers (decimals and
exponentials). The size of float is 4 bytes while the size of double is 8 bytes. Therefore, double has two times
the precision of float.
For example,
float area = 54.90;
double volume = 13457.64534;
As mentioned above, these two data types are also used for exponentials. For example,

PANGASINAN STATE UNIVERSITY 6


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

double distance = 25E14 // 25E14 is equal to 25*10^14

Rules that must be observed when using integers are:


 Plus (+) and minus (-) signs for data of type double are treated exactly as with integers.
 When working with real numbers, however, trailing zeros are ignored.

As with integers, leading zeros should be avoided. Thus, +23.45, 23.45 and 23.450 have the same value, but
023.45 may be interpreted by some C++ compilers as an octal followed by a decimal point which is a syntax
error.

2.3 C++ char


The type char is used to represent character data. In standard C++, data type char can be only a single
character. Character constants of type char must be enclosed in single quotation marks when used in a
program. Otherwise, they are treated as variables and subsequent use may cause compilation error. Thus, to
use the letter A as a constant, you would type ‘A’.

Example: char letter = ‘A’;

2.4 C++ wchar_t


Wide character wchar_t is similar to the char data type, except its size is 2 bytes instead of 1. It is used to
represent characters that require more memory to represent them than a single char.

Example: wchar_t test = L'‫ 'ם‬// storing Hebrew character

Notice the letter L before the quotation marks.

2.5 C++ bool


The bool data type has one of two possible values: true or false. Booleans are used in conditional statements
and loops (which we will learn in the next modules).
Example: bool cond = false;

2.6 C++ void


The void keyword indicates an absence of data. It means “nothing” or “no value”. The void type will be
discussed in more details in the succeeding modules.
Note – We cannot declare variables of the void type.

2.7 C++ Type Modifiers

C++ type modifiers are used to further modify some of the fundamental data types. There are 4 types modifiers
in C++. These are:
1. signed
2. unsigned
3. short
4. long
We can modify the following data types with the above modifiers:
 int

PANGASINAN STATE UNIVERSITY 7


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

 double
 char
The table below shows the C++ modified data types list.
Data Type Size (in Meaning
Bytes)
signed int 4 used for integers (equivalent to int)
unsigned int 4 can only store positive integers
short 2 used for small integers (range -32768 to 32767)
long at least used for large integers (equivalent to long int)
4
unsigned long 4 used for large positive integers or 0 (equivalent
to unsigned long int)
long long 8 used for very large integers (equivalent to long
long int).
unsigned long 8 used for very large positive integers or 0
long (equivalent to unsigned long long int)
long double 8 used for large floating-point numbers
signed char 1 used for characters (guaranteed range -127 to
127)
unsigned char 1 used for characters (range 0 to 255)

Let’s take a look at some examples.

long b = 4523232;
long int c = 2345342;
long double d = 233434.56343;
short d = 3434233; // Error! out of range
unsigned int a = -5; // Error! can only store positive numbers or 0

LEARNING ACTIVITY 4

Activity 1:
Identify the correct data types for the following values:

1. 7500
2. 83.70
3. 77777899.89908
4. 123E12
5. 39
6. A
7. false
8. void main
9. 778900009798321
10. j

Activity 2:
1. Explain the importance of knowing the different data types in C++ programming language.
2. What data type or types you could use when a variable needs to store numeric values?
3. How about if you need to store a letter, whitespace character, or special character in a variable?
4. What would be the appropriate data type for storing the value of the distance between the sun and earth?
Explain why.

PANGASINAN STATE UNIVERSITY 8


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

LEARNING CONTENTS (Variables)

Introduction
In the previous sections of this module, we covered how to select appropriate name and data type of a memory
location. There are two types of memory location that a programmer can declare: variables and named
constants. A variable is a memory location whose value can change during runtime. Most of the memory
locations declared in a program are variables. On the other hand, a named constant is a memory location
whose value cannot be changed during runtime.

In a program that inputs the radius of any circle and then calculates and outputs the circle’s area, a programmer
would declare variables to store the values of the radius and area; doing this allows the values of radius and
area to change while the program is executing. However, he or she would declared a named constant to store
the value of pi (𝜋), which is used in the formula for calculating the area of a circle. (The formula is 𝐴 = 𝜋𝑟 2 ). A
named constant is appropriate in this case since the value of pi (3.141593 when rounded to six decimal places)
will always be the same. Examine the C++ code below:
C++ Code [area.cpp]
#include<iostream>
using namespace std;

int main () {
//This program calculates the area of a circle given its radius
double radius, area;
const double PI = 3.141593;
cout<<"Enter the radius of a circle: ";
cin>>radius;
cout<<"The area of the circle is:" <<PI*radius;
return 0;
}

[Sample Output]
Enter the radius of a circle: 7.5
The area of the circle is: 23.5619

The statement double radius, area; is a declaration of variables named radius and area that can hold
exponential values. While the statement const double PI = 3.141593; is a declaration of named constant
PI that holds a constant value of 3.141593. You will encounter more statements like these in this lesson.

3.1 Variable Declaration


The variable declarations in a C++ program communicate to the C++ compiler the names of all variables used
in a program. Further, they tell the compiler what kind of information will be stored in each variable. C++ a
strongly-typed language, and requires every variable to be declared with its type before its use. This means that
the type of a variable must be known at compile-time (when the program is compiled), and that type cannot be
changed without recompiling the program.

You declare a variable using a statement, which is a C++ instruction that causes the computer to perform some
action after being executed by the computer. A statement that declares a variable causes the computer to
reserve a memory location with the name, data type, and initial value you provide. A variable declaration

PANGASINAN STATE UNIVERSITY 9


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

statement is one of many different types of statements in C++. The declaration of variables is done after the
opening brace of main().

The syntax to declare a new variable in C++ is straightforward: we simply write the type followed by the variable
name (i.e., its identifier). The term syntax refers to the rules of a programming language. For example:

1 int total;
2 float price;

These are two valid declarations of variables. The first one declares a variable of type int with the
identifier total. The second one declares a variable of type float with the identifier price. Once declared,
the variables total and price can be used within the rest of their scope in the program.

If declaring more than one variable of the same type, they can all be declared in a single statement by separating
their identifiers with commas. For example:

int num1, num2, num3;

This declares three variables (num1, num2, and num3), all of them of type int, and has exactly the same
meaning as:

1 int num1;
2 int num2;
3 int num3;

There are two common mistakes that new programmers tend to make (neither serious, since the compiler will
catch these and ask you to fix them) when defining multiple variables of the same type in a single statement:

The first mistake is giving each variable a type when defining variables in sequence.

int num1, int num2, int num3; //wrong (compiler error)

The second mistake is to try to define variables of different types in the same statement, which is not allowed.
Variables of different types must be defined in separate statements.

int num1, double num2, float num3; //wrong (compiler error)

int num1; double num2; float num3; //correct (but not recommended)

//correct and recommended (easier to read)


int num1;
double num2;
float num3;

To see what variable declarations look like in action within a program, let's have a look at the entire C++ code
of the example below:

C++ Code [variables.cpp]


// operating with variables
#include<iostream>
using namespace std;

int main () {

// declaring variables:

PANGASINAN STATE UNIVERSITY 10


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

int num1, num2;


int result;

// process:
num1 = 5;
num2 = 2;
num1 = num1 + 1;
result = num1 - num2;

// print out the result:


cout << result;

// terminate the program:


return 0;
}

[Sample Output]
4

Don't be worried if something else than the variable declarations themselves look a bit strange to you. Most of
it will be explained in more detail in the next modules.

The declaration of a named constant is quite similar to the declaration of variables. To reserve a named
constant, you must follow this syntax:
const datatype constantName = value;
In the syntax, datatype is the type of data the named constant will store, constantName is the identifier of the
constant data, and value is the literal constant that represents the value you want to be stored in a named
constant. The keyword const is used to indicate that the variables value cannot be changed.

Examples:
const int AGE = 65;
const float MAXPAY = 15.75;
const char YES = ‘Y’;

A constant can also be created using the #define preprocessor directive.

LEARNING ACTIVITY 5

Professor Didith wants you to create a program that calculates and displays the volume of a cylinder. The formula
for calculating the volume is V=πr2h. Write the C++ statements that declare the variables and named constant for
this program. Follow the rules in naming your variables and identify their appropriate data types

LEARNING CONTENTS (Variable Initialization and Assignment)

3.2 Variable Initialization and Assignment


In the previous section, we covered how to define a variable that we can use to store values. In this section,
we’ll explore how to actually put values into variables and use those values.
When a variable is defined, you can also provide an initial value for the variable at the same time. This is
called initialization.
Examples:

PANGASINAN STATE UNIVERSITY 11


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

int age = 39;


float rate = 350.70;
char grade = ‘A’ ;
string fName= “Reyes”;
bool answer = false;

In the last section, we noted that it is possible to define multiple variables of the same type in a single statement
by separating the names with a comma:
int num1, num2;
You can initialize multiple variables defined on the same line:
int num1=6, num2=7;

After a variable has been defined, you can give it a value (in a separate statement) using the = operator. This
process is called copy assignment (or just assignment) for short. Take a look at the example below.

int width; // define an integer variable named width


width = 5; // copy assignment of value 5 into variable width

// variable width now has value 5

Copy assignment is named such because it copies the value on the right-hand side of the = operator to the
variable on the left-hand side of the operator. The = operator is called the assignment operator. Using this
operaror, you change the value stored in an existing variable.
Some important rules to follow concerning assignment statements:
1. The assignment is always made from right to left (<-)
2. Constants cannot be on the left side of the assignment symbols.
3. The expression can be a constant, a constant expression, a variable that has previously been
assigned a value, or a combination of variables and constants.
4. Normally, values on the right side of the assignment symbol are not changed by the assignment.
5. The variable and expression must be of compatible data types.
6. Only one value can be stored in a variable at a time, so the previous value of a variable is thrown
away.

We can also make use of compound assignment which is a shorthand form for compound expressions. Refer
to the following examples of compound assignments:
OPERATOR FORM FOR USE EQUIVALENT LONGER FORM
+= x += y x=x+y
-= x -= y x=x–y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y

Here’s an example where we use assignment twice:


C++ Code [assignment.cpp]
#include<iostream>
using namespace std;

int main () {

PANGASINAN STATE UNIVERSITY 12


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

int width;
width = 5; // copy assignment of value 5 into variable width

// variable width now has value 5

width = 7; // change value stored in variable width to 7

// variable width now has value 7

return 0;
}

When we assign value 7 to variable width, the value 5 that was there previously is overwritten. Normal variables
can only hold one value at a time.

The values (5 and 7) that we assigned to the width variable in the code are called literal constants. They are
used to express particular values within the source code of a program. Literal constants can have a data type
that is either numeric, character or string.
A numeric literal constant is simply a number. The numbers 0.0, 2 and 0 are examples of numeric literal
constants. Numeric literal constants can consist only of numbers, plus sign (+), the minus sign (-), the decimal
point (.), and the letter e in uppercase or lowercase (for exponential notation). They cannot contain a space, a
comma, or a special character, such as the dollar sign ($) or the percent sign (%)

A character literal constant is one character enclosed in a single quotation marks. The letter ‘X’ is a character
literal constant, and so are the dollar sign ‘$’ and a space ‘ ’ (two single quotation marks with a space between).

A string literal constant is zero or more characters enclosed in double quotation marks, such as the “Hello”,
the message “Enter room length:”.

When using a literal constant to initialize a memory location in a program, the data type of the literal constant
should match the data type of the memory location to which it is assigned.

When a program instructs the computer to initialize a memory location, the computer first compares the data
type of the value assigned to the memory location with the data type of the memory location itself to verify that
the value is appropriate for the memory location. If the value’s data type does not match the memory location’s
data type, most programming languages use a process called implicit type conversion to convert the value
to fit the memory location.

Type casting which is also known as explicit type conversion, is the explicit conversion of data from one data
type to another. You type cast, or explicitly convert, an item of data by enclosing the data in a parenthesis, and
then preceding it with the C++ keyword that represents the desired data type.

Syntax:
<type name>(expression)

where <type name> is the name of the target type and <expression> evaluates to a type of value that
the cast is capable of converting.

Example:
To type cast the double number 5.5 to the float data type, you would use float(5.5). The float in the type cast
tells the C++ compiler to treat the number within the parentheses as a float data type rather than as a double
data type.

LEARNING ACTIVITY 6

Answer the following:

PANGASINAN STATE UNIVERSITY 13


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

1. What is the difference between initialization and assignment of variables.


2. What happens when we assign a numeric literal constant with floating-point value to an integer variable?
3. Can we change the values on the right side of the assignment operator using an assignment statement? Explain.

LEARNING CONTENTS (Scope and Lifetime)

3.2 Scope and Lifetime


Recall that each variable in modern programming languages has:
 a name: symbolic name used to identify the variable
 an address: the location in memory where variable is stored
 a data type: type and size of data associated with variables
In addition to the above properties, each variable also has:
 a scope: the locations/places/range in the program where the variable is accessible/visible
 a lifetime: the location (i.e., place) where the variable exists
Variables are being created and destroyed while the program is running.

A scope is a region of the program and broadly speaking there are three places, where variables can be
declared:
 Inside a function or a block which is called local variables,
 In the definition of function parameters which is called formal parameters.
 Outside of all functions which is called global variables.
Function and it's parameter will be discussed in the functions module. Here let us explain what are local and
global variables.
Local variables are variables that are declared inside a function or block. They can be used only by statements
that are inside that function or block of code. Local variables are not known to functions outside their own.
Following is the sample program using local variables:
C++ Code [localvariables.cpp]
#include <iostream>
using namespace std;

int main () {
// Local variable declaration:
int a, b;
int c;

// actual initialization
a = 10;
b = 20;
c = a + b;

cout << c;

return 0;
}

Global variables are defined outside of all the functions, usually on top of the program. The global variables
will hold their value throughout the life-time of your program.

PANGASINAN STATE UNIVERSITY 14


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

A global variable can be accessed by any function. That is, a global variable is available for use throughout your
entire program after its declaration. Following is the example using global and local variables:
C++ Code [localglobal.cpp]
#include <iostream>
using namespace std;

// Gloal variable declaration:


int g;

int main () {
// Local variable declaration:
int a, b;

// actual initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}

A program can have same name for local and global variables but value of local variable inside a function will
take preference. For example:
C++ Code [scope.cpp]
#include <iostream>
using namespace std;

// Gloal variable declaration and initialization:


int g=20;

int main () {
// Local variable declaration and initialization:
int g = 10;

cout << g;
return 0;
}
[Sample Output]
10

In the example above, the value of the local variable g which is 10 was displayed instead of 20 which is the
value of the global variable g.
The lifetime of a variable is the location (i.e., place) where the variable exists. Variables are used to store
information. When you need to store some new information, you need to create new variables to hold the
information. Further, information can become irrelevant and no longer needed. So space used to store the
variable need to be reclaimed. This is the time when the variable is destroyed. Thus, programming languages
will need to allow the program to create new variables when they are needed, and also dispose them when
they are no longer necessary.

Lifetime Rules in C++:


 A variable begins to exist when the variable is defined
 A variable stops to exist at the end of the scope in which the variable is defined

This means that a variable exists only locally inside the scope in which it is defined. For this reason, variables
defined inside a scope are called local variables. Furthermore, a local variable can be accessed only after its

PANGASINAN STATE UNIVERSITY 15


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

definition. However, the lifetime of global variables begins to exist when the program starts and stops to exist
when the program exits.

Example:

C++ Code [lifetime.cpp]


#include <iostream>
using namespace std;

int main(int argc, char *argv[])


{

... CANNOT access any variable

int var1; // var1 starts to exist

.. var1 accessible

{
.. var1 accessible

float var2; // var2 starts to exist

var1 and var2 are accessible


} // var2 ends to exist

.. only var1 accessible...


} // var1 ends to exist

float f(float x)
{

... CANNOT access any variable

int var3; // var3 starts to exist

.. var3 accessible

{
.. var3 accessible

float var4; // var4 starts to exist

var3 and var4 are accessible


} // var4 ends to exist

.. only var3 accessible...


}

LEARNING ACTIVITY 7

PANGASINAN STATE UNIVERSITY 16


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC102 Fundamentals of Programming Module No. 3

SUMMARY

In this section, we have covered all the details pertaining to the variables right from selecting a name for the
variables to various scopes of variables in C++. The C++ programming language has a set of rules, called
syntax, which you must follow when using the language. Try to remember the rules discussed in this module
when working with variables as we will be using them in the subsequent modules. Programmers can declare
two types of memory locations which are variables and named constants. The initial value is required when
declaring named constants while it is optional when declaring variables. In most cases, memory locations are
initialized using a literal constant. Make sure that the data type of a literal constant assigned to a memory
location should be the same as the memory location’s type. If the data do not match, the computer performs
automatic type conversion to either promote or demote the value to fit the memory location. Further, the
location where the variable was defined and declared in the program determines its scope and lifetime.

REFERENCES

Zak, D. (2016). An Introduction to Programming with C++ (8E), pages 23-45

Online Reading Materials:


 https://www.softwaretestinghelp.com/variables-in-cpp/#Variable_Scope
 http://www.cplusplus.com/doc/tutorial/variables/
 https://www.programiz.com/cpp-programming/keywords-identifiers
 https://www.learncpp.com/cpp-tutorial/keywords-and-naming-identifiers/
 https://www.programiz.com/cpp-programming/data-types
 https://www.learncpp.com/cpp-tutorial/introduction-to-variables/
 https://www.learncpp.com/cpp-tutorial/variable-assignment-and-initialization/
 https://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm

PANGASINAN STATE UNIVERSITY 17

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy