0% found this document useful (0 votes)
71 views

Week 4-5 PDF

C++ is an object-oriented programming language that is a superset of C and supports both procedural and object-oriented programming. Some key features of C++ include object-oriented programming concepts like encapsulation, inheritance, and polymorphism. C++ also supports features like templates, exceptions, references, and name spaces. C++ is a compiled language that offers libraries and allows for dynamic memory allocation, making it a versatile, high-level language suitable for complex projects.

Uploaded by

Jason Asor
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

Week 4-5 PDF

C++ is an object-oriented programming language that is a superset of C and supports both procedural and object-oriented programming. Some key features of C++ include object-oriented programming concepts like encapsulation, inheritance, and polymorphism. C++ also supports features like templates, exceptions, references, and name spaces. C++ is a compiled language that offers libraries and allows for dynamic memory allocation, making it a versatile, high-level language suitable for complex projects.

Uploaded by

Jason Asor
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Republic of the Philippines

CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE


San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Week 4 and 5
Chapter 2 Language Features

Introduction
C++ is quite similar to C programming. In fact, C++ supports all the features offered
with C with the addition to various other important features like object-oriented
programming, operator overloading, exception and error handling, the namespace feature,
and many more. We can say C++ is the advanced version of C programming. Features of
C++ give multiple reasons to upgrade our skills from C to C++.

• Multi-paradigm language: C++ is a language that supports procedural, object-oriented


and generic programming. This makes it very versatile.
• Use of pointers and references: C+ supports pointers and references that allow the user
to deal directly with the memory and gives all the control to the programmer.
This makes it very suitable for low-level tasks and very complex projects.
• Statically Typed: A language is statically typed if the type of a variable is known at
compile time. For some languages, this means that you as the programmer must
specify what type each variable is. The main advantage here is that all kinds of checking
can be done by the compiler, and therefore a lot of trivial bugs are caught at a very
early stage.
• C++ allows you to specify more than one definition for an operator for different types
(objects?) which is called operator overloading. This allows users to treat even very
complex types as built-in types.
• An interface describes the behavior or capabilities of a C++ class without committing to
a particular implementation of that class. The C# interfaces are implemented using
abstract classes and these abstract classes should not be confused with data
abstraction which is a concept of keeping implementation details separate from
associated data.
• Multiple Inheritance is a feature of C++ where a class can inherit from more than one
classes. The constructors of inherited classes are called in the same order in which they
are inherited. The destructors are called in reverse order of constructors. Multiple
inheritances allow the object to be of multiple types and hence makes real-world
modeling in the program very easy.
• Using ternary operators as values
• The auto keyword that does type deduction automatically without needing the
programmer to interfere.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

2.1 CONCEPT OF C++ FEATURES

Here are some of the remarkable features of C++ language:

1. OOP (Object-Oriented Programming)

C++ is an object-oriented language, unlike C which is a procedural language. This is one of


the most important features of C++. It employs the use of objects while programming. These
objects help you implement real-time problems based on data abstraction, data
encapsulation, data hiding, and polymorphism. We have briefly discussed all the 5 main
concepts of object-oriented programming.
The OOP concepts are:

• Data abstraction: Data abstraction is an act of representing the important


features of data without including the background details or the method applied
to obtain it.
• Data encapsulation: Data encapsulation is nothing but a process to implement
data abstraction by wrapping up the data and functions into an exclusive block.
• Inheritance: The term inheritance refers to transferring the properties of the
parent class to the child class. We can implement the basic idea of inheritance by
creating more than one class, which we formally refer to as derived classes by
linking them with what we call the base class. This concept reduces the
redundancy of the program and makes it easy to transfer/copy the properties of
one class to another
• Data hiding: Data hiding refers to protecting data from unauthorized access. It is
basically responsible for securing the data. It is important to note that data
encapsulation is different from data hiding as encapsulation mainly focuses on
shifting the focus on important data than explaining its complex nature.
• Polymorphism: The word poly means ‘many’ and morphism means ‘forms’.
Clearly, polymorphism refers to displaying that data in more than one form.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

2. Platform or Machine Independent/ Portable

In simple terms, portability refers to using the same piece of code in varied environments.

Let us understand this C++ feature with the help of an example. Suppose you write a piece of
code to find the name, age, and salary of an employee in Microsoft Windows and for some
apparent reason you want to switch your operating system to LINUX. This code will work in a
similar fashion as it did in Windows.

3. Simple

When we start off with a new language, we expect to understand in depth. The simple
context of C++ gives an appeal to programmers, who are eager to learn a new programming
language.
If you are already familiar with C, then you don’t need to worry about facing any trouble
while working in C++. The syntax of C++ is almost similar to that of C. Afterall C++ is referred
to as “C with classes”.

4. High-level programming language

It is important to note that C++ is a high-level programming language, unlike C which is a mid-
level programming language. It makes it easier for the user to work in C++ as a high-level
language as we can closely associate it with the human-comprehensible language, that is,
English.

5. Popular

After learning C, it is the base language for many other popular programming languages
which supports the feature of object-oriented programming. Bjarne Stroustrup found Simula
67, the first object-oriented language ever, lacking simulations and decided to develop C++.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

6. Case sensitive

Just like C, it is pretty clear that the C++ programming language treats the uppercase and
lowercase characters in a different manner. For instance, the meaning of the
keyword ‘cout’ changes if we write it as ‘Cout’ or “COUT”. Other programming languages
like HTML and MySQL are not case sensitive.
7. Compiler-Based

Unlike Java and Python that are interpreter-based, C++ is a compiler based language and
hence it a relatively much faster than Python and Java.

Get a complete guide to master in Python Programming Language


8. DMA (Dynamic Memory Allocation)

Since C++ supports the use of pointers, it allows us to allocate memory dynamically. We may
even use constructors and destructors while working with classes and objects in C++.

9. Existence of Libraries

The C++ programming language offers a library full of in-built functions that make things easy
for the programmer. These functions can be accessed by including suitable header files.

10. Speed

As discussed earlier, C++ is compiler-based hence it is much faster than other programming
languages like Python and Java that are interpreter-based.

2.2 Difference between C and C++

C C++

C was developed by Dennis Ritchie between C++ was developed by Bjarne Stroustrup in
1969 and 1973 at AT&T Bell Labs. 1979 with C++'s predecessor "C with
Classes".

When compared to C++, C is a subset of C++. C++ is a superset of C. C++ can run most of C
code while C cannot run C++ code.

C supports procedural programming C++ supports both procedural and object-


paradigm for code development. oriented programming paradigms;
therefore, C++ is also called a hybrid
language.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

C does not support object-oriented Being an object-oriented programming


programming; therefore it has no support for language C++ supports polymorphism,
polymorphism, encapsulation, and encapsulation, and inheritance.
inheritance.

In C (because it is a procedural programming In C++ (when it is used as object-oriented


language), data and functions are separate programming language), data and functions
and free entities. are encapsulated together in form of an
object. For creating objects class provides a
blueprint of structure of the object.

In C, data are free entities and can be In C++, Encapsulation hides the data to
manipulated by outside code. This is because ensure that data structures and operators
C does not support information hiding. are used as intended.

C, being a procedural programming, it is a While, C++, being an object oriented


function driven language. programming, it is an object driven
language.

C does not support function and operator C++ supports both function and operator
overloading. overloading.

C does not allow functions to be defined In C++, functions can be used inside a
inside structures. structure.

C does not have namespace feature. C++ uses NAMESPACE which avoid name
collisions.
A namespace is a declarative region that
provides a scope to the identifiers (the
names of types, functions, variables, etc)
inside it. Namespaces are used to organize
code into logical groups and to prevent
name collisions that can occur especially
when your code base includes multiple
libraries. All identifiers at namespace scope
are visible to one another without
qualification. Identifiers outside the
namespace can access the members by
using the fully qualified name for each
identifier.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

C uses functions for input/output. For C++ uses objects for input output. For
example scanf and printf. example cin and cout.

C does not support reference variables. C++ supports reference variables.

C has no support for virtual and friend C++ supports virtual and friend functions.
functions.

C provides malloc() and calloc() functions for C++ provides new operator for memory
dynamic memory allocation, and free() for allocation and delete operator for memory
memory de-allocation. de-allocation.

C does not provide direct support for error C++ provides support for exception handling.
handling (also called exception handling) Exceptions are used for "hard" errors that
make the code incorrect.

Key Differences Between C Vs C++


Enlisted below are the main differences between C Vs C++.

#1) Type of Programming:


C is a procedural language in which the program revolves around the functions. The entire
problem is broken down into numerous functions. The main focus of the program is on
functions or procedures to get the things done.

C++, on the contrary, is an object-oriented programming language. Here the data of the
problem is the main focus and the classes are built around this data. Functions operate on
the data and closely bound to data.

#2) Programming Approach:


As C is a procedural language, it follows a top-down approach of programming. Here we take
the problem and then break it into subproblems until we find single subproblems that can be
solved directly. Then we combine the solutions to get the main solution.

C++ follows a bottom-up approach to programming. In this, we start with low-level design or
coding and then build on this low-level design to get a high-level solution.

#3) Application Development:


C language is helpful in the programming of embedded systems or low-level
implementations.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

C++, on the other hand, is more suitable for server-side applications, network applications or
for applications like gaming, etc.

#4) File Extension:


The programs written in C are usually saved with “.c” extension while the C++ programs are
saved with the “.cpp” extension.

#5) Compatibility With Each Other:


C++ is a subset of C as it is developed and takes most of its procedural constructs from the C
language. Thus any C program will compile and run fine with the C++ compiler.

However, C language does not support object-oriented features of C++ and hence it is not
compatible with C++ programs. Therefore programs written in C++ will not run on C
compilers.

#6) Compatibility With Other Languages:


C++ language is generally compatible with other generic programming languages but C
language is not.

#7) Ease of Coding:


We can say that C is a hands-on language and we can program it in whichever way we want.
C++ consists of some high-level object-oriented programming constructs that help us to code
high-level programs.

Thus if we say C is easy then C++ is also easier to code.

#8) Data Security:


In C, the main emphasis is on functions or procedures rather than on data. Hence as far as
data security is concerned, it is negligible in C.

In C++, as we are dealing with classes and objects, the main building block of the program is
Data. Thus, data is tightly secured using classes, access specifiers, encapsulation, etc.

#9) Program Division:


A program in C is divided into functions and modules. These functions and modules are then
called by the main function or other functions for execution.

A C++ program is divided into classes and objects. The problem is designed into classes and
the objects of these classes are the executing units that are created by the main functions
and are executed.

#10) Standard I/O Operations:


The standard input-output operations in C to read/write data from/to the standard device
are ‘scanf’ and ‘printf’ respectively.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

In C++, the data is read from the standard input device using ‘cin’ while it is printed to the
output device using ‘cout’.

#11) Focus/Emphasis:
Being a procedural language, C has more emphasis on the sequence of steps or procedures
to solve a problem.

C++, on the other hand, is object-oriented and thus puts more focus on objects and classes
around which the solution is to be built.

#12) The main() Function:


In C++ we cannot call a main() function from any other point. The main() function is the single
execution point.

However, in C language, we can have a main() function called by the other functions in the
code.

#13) Variable:
Variables need to be declared at the beginning of the function block in C, on the contrary, we
can declare variables anywhere in a C++ program provided they are declared before they are
used in the code.

#14) Global Variables:


C language allows multiple declarations of global variables. C++, however, doesn’t allow
multiple declarations of global variables.

#15) Pointers And Reference Variables:


Pointers are the variables that point to memory addresses. Both C and C++ support pointers
and various operations performed on pointers.

References act as aliases for the variables and point to the same memory location as a
variable.

C language only supports pointers and not references. C++ supports pointers as well as
references.

#16) Enumerations:
We can declare enumerations in C as well as C++. But in C, the enumeration constants are of
Integer type. It is the same as declaring an integer constant without any type of safety.

In C++, the enumerations are different. They are of distinct types. Thus to assign an integer
type to a variable of an enumerated type, we need explicit type conversion.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

However, we can assign an enumerated value to a variable of integer type as enumerated


type allows integral promotion or implicit conversion.

#17) Strings:
As far as strings are concerned, the declaration ‘char []’ declares a string array. But when the
string declared as above is passed between the functions, then there is no guarantee that it
will not be changed by the other external functions as these strings are mutable.

This drawback is not there in C++ as C++ supports string data type that defines immutable
strings.

#18) Inline Function:


Inline functions are not supported in C. C usually works with macros to speed up the
execution. In C++ on the other hand, inline functions, as well as macros, are used.

#19) Default Arguments:


Default arguments/parameters are used when the parameters are not specified at the time
of the function call. We specify default values for parameters in the function definition.

The C language does not support default parameters. Whereas C++ supports the use of
default arguments.

#20) Structures:
Structures in C and C++ use the same concept. But the difference is, in C, as we cannot
include functions as members.

C++ allows structures to have functions as its members.

#21) Classes & Objects:


C is a procedural language and hence it does not support the concept of classes and objects.

On the other hand, C++ supports the concept of classes and objects and almost all the
applications in C++ are built around classes and objects.

#22) Data Types:


C supports built-in and primitive data types. Contrary to this, C++ supports user-defined data
types in addition to built-in and primitive data types.

Apart from this C++ also supports Boolean and string data types which are not supported by
C.

#23) Function Overloading:


Function overloading is the ability to have more than one function with the same name but
different parameters or a list of parameters or order of parameters.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

This is an important feature of object-oriented programming and is present in C++. However,


C does not support this feature.

#24) Inheritance:
Inheritance is also an important feature of object-oriented programming that is supported by
C++ and not C.

#25) Functions:
C does not support functions with default arrangements like default parameters etc. C++
supports functions with default arrangements.

#26) Namespace:
Namespaces are not supported in C but are supported by C++.
#27) Source Code:
C is a free-format language that gives us the ability to program anything. C++ is derived from
C and also has object-oriented programming features which make it more efficient as far as
the source code is concerned.

#28) Abstraction:
Abstraction is the way to hide the implementation details and expose only the required
interface to the user. This is one of the distinguishing features of Object-oriented
programming.

C++ supports this feature while C does not.

#29) Encapsulation:
Encapsulation is a technique using which we encapsulate the data from the outside world.
This aids in information hiding.

C++ uses classes which bundle data and the functions operating on this data in a single unit.
This is encapsulation. C does not have this feature.

#30) Information Hiding:


The features of abstraction and encapsulation can aid in information hiding by exposing only
the required details and hiding the details like implementation, etc., from the user. This way
we can enhance the security of data in our programs.

C++ puts great emphasis on data and uses abstraction and encapsulation for information
hiding.

C doesn’t put any emphasis on data and does not deal with information hiding.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

#31) Polymorphism:
Polymorphism simply means that one object has many forms and it is an essential feature of
object-oriented programming. Being an object-oriented language, C++ supports
polymorphism.

C has no support for object-oriented programming and does not support polymorphism.
However, we can simulate the dynamic dispatch of functions in C using function pointers.

#32) Virtual Function:


Virtual functions which are also called as Runtime polymorphism is a technique that is used
to resolve function calls at runtime. This is yet another feature of object-oriented
programming which is supported by C++ and not by C.

#33) GUI Programming:


For programming related to GUI (Graphical User Interface), C uses Gtk tools while C++ uses
Qt tools.

#34) Mapping:
As far as the mapping of data with functions is concerned, C language is very complicated as
it does not keep any focus on data.

Whereas C++ has a good mapping of data and functions as it supports classes and objects
that bind data and functions together.

#35) Memory Management:


Both C and C++ have manual memory management but how memory management is done is
different in both languages.

In C we use functions like malloc (), calloc (), realloc (), etc., to allocate memory and free ()
function to free the memory. But, in C++, we use new () and delete () operators to allocate
and deallocate the memory respectively.

#36) Default Headers:


Default headers contain the common function calls that are used in programming languages
mainly for input-output etc.

In C, ‘stdio.h’ is the default header used while C++ uses <iostream> as the default header.
#37) Exception/Error Handling:
C++ supports exception/error handling using the try-catch blocks. C doesn’t support
exception handling directly but we can handle errors using some workaround.

#38) Keywords:
C++ supports a lot more keywords than that of C. In fact, C has only 32 keywords whereas
C++ has 52 keywords.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

#39) Templates:
Templates allow us to define classes and objects independent of the data type. Using
templates, we can write generic code and call it for any data type.

C++ being object-oriented uses classes and objects and thus supports templates. C, on the
other hand, doesn’t support the concept of templates.

Tabular Format: C Vs C++


No Characteristics C C++

1 Type of programming Procedural language Object-Oriented programming language.

2 Programming Top-down approach Bottom-up approach


Approach

3 Application Good for embedded devices, Good for networking, server-side


development system-level coding etc. applications, gaming, etc.

4 File Extension .c .cpp

5 Compatibility with Not Compatible with C++. Compatible with C as C++ is a subset of C.
each other

6 Compatibility with Not compatible Compatible


other languages

7 Ease of coding Allows us to code everything. Comes with highly advanced Object-
Oriented concepts.

8 Data Security Negligible High

9 Program division Program divided into Program divided into classes and objects.
functions.

10 Standard I/O scanf/printf cin/cout


operations
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

No Characteristics C C++

11 Focus/emphasis Emphasizes on functions Emphasizes on data rather than functions.


and/or processes.

12 The main() function Can call main through other Not possible to call main from any point.
functions.

13 Variables To be declared at the Can be declared anywhere in the program.


beginning of the function.

14 Global variables Multiple declarations No multiple declarations.

15 Reference Variables Only Pointers Both


and pointers

16 Enumerations Only integer types. Distinct type

17 Strings Supports only char[] Supports string class which is immutable.

18 Inline function Not supported Supported

19 Default arguments Not supported Supported

20 Structures Cannot have functions as Can have functions as structure members.


structure members.

21 Classes and Objects Not supported Supported

22 Data Types Only built-in and primitive Boolean and string types supported in
data types are supported. addition to built-in data types.
No Boolean and string types.

23 Function overloading Not supported Supported

24 Inheritance Not supported Supported


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

No Characteristics C C++

25 Functions Does not support functions Supports functions with default


with default arrangements. arrangements.

26 Namespace Not supported Supported

27 Source code Free-format Originally taken from C plus object-oriented.

28 Abstraction Not present Present

29 Information hiding Not supported Supported

30 Encapsulation Not supported Supported

31 Polymorphism Not supported Supported

32 Virtual function Not supported Supported

33 GUI programming Using the Gtk tool. Using the Qt tools.

34 Mapping Cannot easily map data and Data and functions can be easily mapped.
functions.

35 Memory management Malloc(), calloc(), free() New() and delete() operators.


functions.

36 Default headers Stdio.h iostream header

37 Exception/error No direct support. Supported


handling

38 Keywords Supports 32 keywords. Supports 52 keywords.

39 Templates Not supported Supported


Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

2.3 VARIABLES DECLARATION IN C++


A variable provides us with named storage that our programs can manipulate. Each variable
in C++ has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It
must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because C++ is case-sensitive −

Sr.No Type & Description

1
bool
Stores either value true or false.

2
char
Typically a single octet (one byte). This is an integer type.

3
int
The most natural size of integer for the machine.

4
float
A single-precision floating point value.

5
double
A double-precision floating point value.

6
void
Represents the absence of type.

7
wchar_t
A wide character type.

C++ also allows to define various other types of variables, which we will cover in subsequent
chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes.
Following section will cover how to define, declare and use various types of variables.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Variable Definition in C++


A variable definition tells the compiler where and how much storage to create for the variable.
A variable definition specifies a data type, and contains a list of one or more variables of that
type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any
user-defined object, etc., and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the
compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables is
undefined.
Variable Declaration in C++
A variable declaration provides assurance to the compiler that there is one variable existing
with the given type and name so that compiler proceed for further compilation without
needing complete detail about the variable. A variable declaration has its meaning at the time
of compilation only, compiler needs actual variable definition at the time of linking of the
program.
A variable declaration is useful when you are using multiple files and you define your variable
in one of the files which will be available at the time of linking of the program. You will
use extern keyword to declare a variable at any place. Though you can declare a variable
multiple times in your C++ program, but it can be defined only once in a file, a function or a
block of code.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Example
Try the following example where a variable has been declared at the top, but it has been
defined inside the main function −

#include <iostream>
using namespace std;

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {
// Variable definition:
int a, b;
int c;
float f;

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

cout << c << endl ;

f = 70.0/3.0;
cout << f << endl ;

return 0;
}
When the above code is compiled and executed, it produces the following result −
30
23.3333
Same concept applies on function declaration where you provide a function name at the time
of its declaration and its actual definition can be given anywhere else. For example −
// function declaration
int func();
int main() {
// function call
int i = func();
}

// function definition
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

int func() {
return 0;
}
Lvalues and Rvalues
There are two kinds of expressions in C++ −
• lvalue − Expressions that refer to a memory location is called "lvalue" expression. An
lvalue may appear as either the left-hand or right-hand side of an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some address in
memory. An rvalue is an expression that cannot have a value assigned to it which
means an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so may not be assigned and can not appear on the left-hand side.
Following is a valid statement −
int g = 20;
But the following is not a valid statement and would generate compile-time error −
10 = 20;

There are some rules that must be in your knowledge to work with C++ variables.

Rules of Declaring variables in C++

• A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and
the underscore character.
• The first character must be a letter or underscore.
• Blank spaces cannot be used in variable names.
• Special characters like #, $ are not allowed.
• C++ keywords cannot be used as variable names.
• Variable names are case-sensitive.
• A variable name can be consisting of 31 characters only if we declare a variable more
than one characters compiler will ignore after 31 characters.
• Variable type can be bool, char, int, float, double, void or wchar_t.
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

Local Variables
Variables that are declared inside a function or block are local variables. 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 example using local variables −

#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
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.
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 −

#include <iostream>
using namespace std;

// Global variable declaration:


int g;

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

// actual initialization
a = 10;
b = 20;
g = a + b;
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

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 −

#include <iostream>
using namespace std;

// Global variable declaration:


int g = 20;

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

cout << g;

return 0;
}
When the above code is compiled and
executed, it produces the following result

10
Initializing Local and Global Variables
When a local variable is defined, it is not
initialized by the system, you must
initialize it yourself. Global variables are
initialized automatically by the system when you define them as follows −

Data Type Initializer

int 0

char '\0'

float 0

double 0
Republic of the Philippines
CENTRAL BICOL STATE UNIVERSITY OF AGRICULTURE
San Jose, Pili, Camarines Sur 4418
ISO 9001:2015 www.cbsua.edu.ph
TÜV-R 01 100 1934918

pointer NULL

Learning Resources
1. CBSUA Website
2. Student Handbook
3. Fundamentals of Computing 1 (SY 2020-2021) Syllabus
4. Google.com
5. PowerPoint Presentation

Uploaded in this Google Drive Folder.

Tasks/Activities

• Lecture Discussion (Zoom/Google Meet) – Recorded


• PowerPoint Presentation
• Video Clips
• Quiz via google doc

Discussion Board

A Facebook group chat will be created where the students can discuss their ideas and thoughts. Chat
in Facebook Group allow us to communicate between users in a chat channel. Virtual Learning Portal
(VLP) will be the main source of lessons on the topic. This platform will be utilized throughout the
course.

Competency Checklist (Formative Assessment/Diagnostic)

The student will be assessed by filling out a questionnaire in google doc regarding the lessons that
have been presented. This assessment will determine the knowledge that they’ve learned with the
Video Lectures Presentation.
Instructions:

1. This is an individual activity.


2. Login to their institutional account
3. Check updated assessment

Tasks/Activities

• Answer the questionnaire


• Video presentation PowerPoint Presentation
• Video Clips

You might also like