Sie sind auf Seite 1von 26

National Institute of Electronics and Information Technology (NIELIT), Kolkata

C/C++
Topics Covered: Unit 1 -Variables and Functions

• How does a C++ program execute?

1 (07.01.2019, 11.01.2019, 14.01.2019)


As C++ is directly developed from C, hence we can say that C++ is a superset of C. Therefore,
most constructs of Care legal in C++ with their meaning unchanged. However, there are some
exceptions and additions.

1. Tokens:
The smallest individual units in a program is known as tokens. C++ has the following set of tokens:
• Keywords
• Identifiers
• Constants
• Strings
• Operators
Generally, a C++ program is written using these tokens, whitespaces and predefined syntaxes. Most
of the C++ tokens are similar to that of the C, with some minor differences.

2. Keywords:
Keywords are a set of predefined words, which carries the responsibilities of specific features. These
keywords are reserved identifiers, and hence cannot be used anywhere except for their reserved tasks.
They also cannot be used as the name of any variable or user defined elements.
C and C++ holds the similar set of keywords defined by the ANSI (American National Standards
Institute) C standards, with some modified keywords for extended C++ features and OOP specified
operations.
Later on, the ANSI C++ committee has added another new set of keywords to C++ for the enhancement
and versatility of this language.

2 (07.01.2019, 11.01.2019, 14.01.2019)


3. Identifiers and Constants:
Identifiers are the names of the variables, functions, arrays, classes etc. created by the programmers
while coding the program. Identifiers help to identify and distinguish between different user specified
elements of a program.

Like each language, C++ also has its own rule for naming the identifiers:
• Only alphabetic characters. digits and underscores are permitted.
• The name cannot start with a digit.
• Uppercase and lowercase letters are distinct.
• A declared keyword cannot be used as a variable name.

The major differences between C and C++ identifiers and naming convention is that apparently C++
has no restrictions in identifier naming. While C supports up to 32 characters for naming, C++ does
not have any such restriction. Hence, all the characters in C++ identifiers naming are equally
significant.

Identifiers such as variable names can start with any letter of the alphabet or an underscore. Next comes
a letter, a digit, or an underscore. The underscore can be used to enhance the readability of a variable
name, as in line_count. Since C++ is s “strongly typed language”, uppercase and lowercase are seen
as different; i.e., to C++, myvar and MyVar are separate names. There is one important identifier
restriction: we cannot use any of the C++ keywords as identifier names. In addition, predefined
identifiers such as cout are also off limits.

4. Data Types in C++:


• Importance of Data Types:
The data type of a variable is important because it determines the operations that are allowed and the
range of values that can be stored. C++ defines several types of data, and each type has unique
characteristics. Because data types differ, all variables must be declared prior to their use, and a
variable declaration always includes a type specifier. The compiler requires this information in order
to generate correct code. In C++ there is no concept of a “type-less” variable.
A second reason that data types are important to C++ programming is that several of the basic types
are closely tied to the building blocks upon which the computer operates: bytes and words. Thus, C++
lets us to operate on the same types of data as does the CPU itself. This is one of the ways that C++
enables us to write very efficient, system-level code.

3 (07.01.2019, 11.01.2019, 14.01.2019)


• Versatility of C++ Data Types:
C++ provides built-in data types that correspond to integers, characters, floating-point values, and
Boolean values. These are the ways that data is commonly stored and manipulated by a program.
In our later topics, we will see that C++ also allows us to construct more sophisticated types, such as
classes, structures, and enumerations, but these too are ultimately composed of the built-in types.

• The hierarchy of C++ datatypes can be elaborated as following:

C++ allows certain of the basic types to have modifiers preceding them. A modifier alters the meaning
of the base type so that it more precisely fits the needs of various situations. The data type modifiers
are as following:
• signed
• unsigned
• long
• short

The modifiers signed, unsigned, long, and short can be applied to int. The modifiers signed and
unsigned can be applied to the char type. The type double can be modified by long.

4 (07.01.2019, 11.01.2019, 14.01.2019)


Both C and C++ compilers support all the built-in (also known as basic or fundamental) data types.
with the exception of void, the basic data types may have several modifiers preceding them to serve
the needs of various situations. The modifiers signed, unsigned, long, and short may be applied to
character and integer basic data types. However, the modifier long may also be applied to double. Data
type representation is machine specific in C++.

• The classification of the basic or built-in C++ datatypes can further be elaborated as
follows:

5 (07.01.2019, 11.01.2019, 14.01.2019)


The type void was introduced in ANSI C. Two normal uses of void are:
1. To specify the return type of a function when it is not returning any value, and
2. To indicate an empty argument list to a function.

variables of type int hold integer quantities that do not require fractional components. Variables of this
type are often used for controlling loops and conditional statements, and for counting. Because they
don’t have fractional components, operations on int quantities are much faster than they are on floating-
point types.

• Integer Type:
Integer variables represent integer numbers like 1, 30,000, and –27. Such numbers are used for
counting discrete numbers of objects, like 11 pencils or 99 bottles of beer. Unlike floating point
numbers, integers have no fractional part; we can express the idea of four using integers, but not four
and one-half.

Because integers are so important to programming, C++ defines several varieties. There are short,
regular, and long integers. Furthermore, there are signed and unsigned versions of each. A signed
integer can hold both positive and negative values. By default, integers are signed. Thus, the use of
signed on integers is redundant (but allowed) because the default declaration assumes a signed value.
An unsigned integer can hold only positive values. To create an unsigned integer, use the unsigned
modifier.

The difference between signed and unsigned integers is in the way the high-order bit of the integer is
interpreted. If a signed integer is specified, then the C++ compiler will generate code that assumes that
the high-order bit of an integer is to be used as a sign flag. If the sign flag is 0, then the number is
positive; if it is 1, then the number is negative. Negative numbers are almost always represented using
the two’s complement approach. In this method, all bits in the number (except the sign flag) are
reversed, and then 1 is added to this number. Finally, the sign flag is set to 1.

Signed integers are important for a great many algorithms, but they have only half the absolute
magnitude of their unsigned relatives. For example, assuming a 16-bit integer, here is 32,767:
0111111111111111
For a signed value, if the high-order bit were set to 1, the number would then be interpreted as –1
(assuming the two’s complement format). However, if we declared this to be an unsigned int, then
when the high-order bit was set to 1, the number would become 65,535.

6 (07.01.2019, 11.01.2019, 14.01.2019)


• Defining an Integer Variable:

Integer variables exist in several sizes, but the most commonly used is type int. The amount of memory
occupied by the integer types is system dependent.
On a 32-bit system such as Windows, an int occupies 4 bytes (which is 32 bits) of memory. This allows
an int to hold numbers in the range from –2,147,483,648 to 2,147,483,647.
While type int occupies 4 bytes on current Windows computers, it occupied only 2 bytes in MS-DOS
and earlier versions of Windows. The ranges occupied by the various types are listed in the header file
LIMITS; we can also look them up using our compiler’s help system.
We demonstrate a program that defines and uses several variables of type int:
#include <iostream>
using namespace std;
int main()
{
int var1; //define var1
int var2; //define var2
var1 = 20; //assign value to var1
var2 = var1 + 10; //assign value to var2
cout << “var1+10 is “; //output text
cout << var2 << endl; //output value of var2
return 0;
}

We must declare a variable before using it. However, we can also place variable declarations anywhere
in a program. It’s not necessary to declare variables before the first executable statement (as was
necessary in C).

• Character Type:

Character data types are used for saving character codes. A character code is an integer associated with
each character. The letter A is represented by code 65, for example. The character set defines which
code represents a certain character. When displaying characters on screen, the applicable character
codes are transmitted and the “receiver,” that is the screen, is responsible for correctly interpreting the
codes.

The C++ language does not stipulate any particular characters set, although in general a character set
that contains the ASCII code (American Standard Code for Information Interchange) is used. This 7-
bit code contains definitions for 32 control characters (codes 0 – 31) and 96 printable characters (codes
32 – 127).

7 (07.01.2019, 11.01.2019, 14.01.2019)


The char (character) type is used to store character codes in one byte (8 bits). This amount of storage
is sufficient for extended character sets, for example, the ANSI character set that contains the ASCII
codes and additional characters.

The wchar_t (wide character type) type comprises at least 2 bytes (16 bits) and thus capable of storing
modern Unicode characters. Unicode is a 16-bit code also used in Windows NT and containing codes
for approximately 35,000 characters in 24 languages.

To specify a character, we must enclose it between single quotes. Thus, this assigns X to the variable
ch:
char ch;
ch = 'X';
We can output a char value using a cout statement. For example, this line outputs the value in ch:
cout << "This is ch: " << ch;
This results in the following output:
This is ch: X
The char type can be modified with signed or unsigned. Technically, whether char is signed or
unsigned by default is implementation-defined. However, for most compilers char is signed. In these
environments, the use of signed on char is also redundant. For the rest of this book, it will be assumed
that chars are signed entities.

We demonstrate a program to show some examples of character constants and variables.

#include <iostream> //for cout, etc.


using namespace std;
int main()
{
char charvar1 = ‘A’; //define char variable as character
char charvar2 = ‘\t’; //define char variable as tab
cout << charvar1; //display character
cout << charvar2; //display character
charvar1 = ‘B’; //set char variable to char constant
cout << charvar1; //display character
cout << ‘\n’; //display newline character
return 0;
}

Also, Strings can be stated as the cumulation of constants.

8 (07.01.2019, 11.01.2019, 14.01.2019)


• Floating Type:

Numbers with a fraction part are indicated by a decimal point in C++ and are referred to as floating-
point numbers. In contrast to integers, floating-point numbers must be stored to a preset accuracy. The
following three types are available for calculations involving
• floating-point numbers:
• float for simple accuracy
• double for double accuracy
• long double for high accuracy
The value range and accuracy of a type are derived from the amount of memory allocated and the
internal representation of the type. Accuracy is expressed in decimal places. This means that “six
decimal places” allows a programmer to store two floating-point numbers that differ within the first
six decimal places as separate numbers. In reverse, there is no guarantee that the figures 12.3456 and
12.34561 will be distinguished when working to a accuracy of six decimal places. Also remember, it
is not a question of the position of the decimal point, but merely of the numerical sequence.
If it is important for wer program to display floating-point numbers with an accuracy supported by a
particular machine, we should refer to the values defined in the cfloat header file.

We demonstrate a program to calculate the length of the hypotenuse using the Pythagoras theorem:

9 (07.01.2019, 11.01.2019, 14.01.2019)


• Boolean (bool) Type:

The bool type is a relatively recent addition to C++. It stores Boolean (that is, true/false) values. C++
defines two Boolean constants, true and false, which are the only two values that a bool value can
have.
The result of a comparison or a logical association using AND or OR is a boolean value, which can be
true or false. C++ uses the bool type to represent boolean values. An expression of the type bool can
either be true or false, where the internal value for true will be represented as the numerical value 1
and false by a zero.
It is important to understand how true and false are defined by C++. One of the fundamental concepts
in C++ is that any nonzero value is interpreted as true and zero is false. This concept is fully compatible
with the bool data type because when used in a Boolean expression, C++ automatically converts any
nonzero value into true. It automatically converts zero into false. The reverse is also true; when used
in a non-Boolean expression, true is converted into 1, and false is converted into zero.

Program to demonstrate Boolean values using a variable:

10 (07.01.2019, 11.01.2019, 14.01.2019)


A boolean expression can have two values that are identified by the keywords true and false.
Both constants are of the bool type. They can be used, for example, to set flags representing
just two states.

• Constants:

The boolean keywords true and false, a number, a character, or a character sequence (string) are all
constants, which are also referred to as a literal. Constants can thus be subdivided into
■ boolean constants
■ numerical constants
■ character constants
■ string constants.

Every constant represents a value and thus a type—as does every expression in C++. The type is
defined by the way the constant is written.

• Boolean Constants:

A boolean expression can have two values that are identified by the keywords true and false. Both
constants are of the bool type. They can be used, for example, to set flags representing just two states.

• Integral Constants:

Integral numerical constants can be represented as simple decimal numbers, octal, or hexadecimals:
■ a decimal constant (base 10) begins with a decimal number other than zero, such as 109 or 987650,
■ an octal constant (base 8) begins with a leading 0, for example 077 or 01234567,
■ a hexadecimal constant (base 16) begins with the character pair 0x or 0X, for example 0x2A0 or
0X4b1C. Hexadecimal numbers can be capitalized or noncapitalized.
Integral constants are normally of type int. If the value of the constant is too large for the int type, a
type capable of representing larger values will be applied. The ranking for decimal constants is as
follows:
int, long, unsigned long

11 (07.01.2019, 11.01.2019, 14.01.2019)


We can designate the type of a constant by adding the letter L or l (for long), or U or u (for unsigned).
For example,
12L and 12l correspond to the type long
12U and 12u correspond to the type unsigned int
12UL and 12ul correspond to the type unsigned long

• Floating-Point Constants:

Floating-point numbers are always represented as decimals, a decimal point being used to distinguish
the fraction part from the integer part. However, exponential notation is also permissible.
EXAMPLES: 27.1 1.8E–2 // Type: double
Here, 1.8E–2 represents a value of 1.8*10–2. E can also be written with a small letter e.g. A decimal
point or E (e) must always be used to distinguish floating-point constants from integer constants.
Floating-point constants are of type double by default. However, we can add F or f to designate the
float type, or add L or l for the long double type.

• Character Constants:

A character constant is a character enclosed in single quotes. Character constants take the type char.
EXAMPLE: 'A' // Type: char
The numerical value is the character code representing the character. The constant 'A' thus has a value
of 65 in ASCII code.

• String Constants:

We already know string constants, which were introduced for text output using the cout stream. A
string constant consists of a sequence of characters enclosed in double quotes.
EXAMPLE: "Today is a beautiful day!"
A string constant is stored internally without the quotes but terminated with a null character, \0,
represented by a byte with a numerical value of 0 — that is, all the bits in this byte are set to 0. Thus,
a string occupies one byte more in memory than the number of characters it contains. An empty string,
"", therefore occupies a single byte.
The terminating null character \0 is not the same as the number zero and has a different character code
than zero. Thus, the string

12 (07.01.2019, 11.01.2019, 14.01.2019)


EXAMPLE: "0"
comprises two bytes, the first byte containing the code for the character zero 0 (ASCII code 48) and
the second byte the value 0.
The terminating null character \0 is an example of an escape sequence. Escape sequences are described
in the following section.

Special Characters and Escape Sequences:

13 (07.01.2019, 11.01.2019, 14.01.2019)


• Volatile Objects:

The keyword volatile, which is rarely used, creates variables that can be modified not only by the
program but also by other programs and external events. Events can be initiated by interrupts or by a
hardware clock.
EXAMPLE: volatile unsigned long clock_ticks;
Even if the program itself does not modify the variable, the compiler must assume that the value of the
variable has changed since it was last accessed. The compiler thereforecreates machine code to read
the value of the variable whenever it is accessed instead of repeatedly using a value that has been read
at a prior stage. It is also possible to combine the keywords const and volatile when declaring a
variable.
EXAMPLE: volatile const unsigned time_to_live;
Based on this declaration, the variable time_to_live cannot be modified by the program but by external
events.

• Type Compatibility:

C++ is strict with regard to type compatibility as compared to C. For instance, C++ defines int, short
int, and long int as three different types. They must be cast when their values are assigned to one
another. Similarly, unsigned char, char, and signed char are considered as different types, although
each of three has a size of one byte. In C++, the types of values must be the same for complete
compatibility. or else. a cast mu.st be applied. These restrictions in C++ are necessary in order to
support function overloading where two functions with the same name are distinguished using the type
of function argument.&. Another notable difference is the way char constants are stored. In C, they are
stored as: int, and therefore,
size<if ('x')
is equivalent to
sizeof(int)
in C. ln C++, however, char is not pron1oted to the size of int and therefore
sizeof(' x ' )
equals
sizeof (char}

14 (07.01.2019, 11.01.2019, 14.01.2019)


• Referencing a Variable:

C++ introduces a new kind of variable known as the reference variable. A reference variable provides
an alias (alternative name) for a previously defined variable. For example, if we make the variable sum
a reference to the variable total, then sum and total can be used
inLengthangeablyt<l represents that variable. A reference variable is created as follows:
data-type & reference-name = variable-name

A reference variable must be initialized at the time of declaration. This establishes the correspondence
between the reference and the data object which it names. It is important to note that the initialization
of a reference variable is completely different from assignment to lt.

C++ assigns additional meaning to the symbol &. Here. & is not an address operator. The notation
float & means reference to float. Other examples are:
int n[10];
int & x = n[ 10] ;
char & a = ' \ n' ; // initialize reference to a literal

The variable x is an alternative to the array element n[10]. The variable a is initialized to the newline
constant. This creates a reference to the otherwise unknown location where the newline constant \ n is
stored.
The following references are also allowed:
i. int x;
int *p = & x ;
int & m = *p;
ii. int & n = 50;
The first set of declarations causes m to refer to x which is pointed to by the pointer p and the statement
in ii creates an int object with value 50 and name n.
• User Defined Data Types:

▪ Class and Structures:

15 (07.01.2019, 11.01.2019, 14.01.2019)


We have used user-defined data types such as struct and union in C. While these data types are legal
in C++. some more features have been added to make them suitable for object-oriented programming.
C++ also permits us to define another user-defined data type known as class which can be used, just
like any other basic data type, to declare variables. The class variables are known as objects, which are
the central focus of object-oriented programming.

Main differences between class and structure:

A class in C++ is just an extension of a structure used in the C language. It is a user defined data
type. It actually binds the data and its related functions in one unit. As structure and a class in C
language differs a lot as a structure has limited functionality and features as compared to a class. On
the other hand, structure and class in C++ are quite similar. The main difference arises due to the fact
that by default, all the members of a class are private, whereas by default all the members of a
structure are public.
Structure is also a user defined data type with a certain template. It is generally used for grouping of
logically related data items. After the creation of a structure, the variables pertaining to the type of
structure can be defined and used. A structure is used to represent a record. In C++, a structure can
have both data members and functions as classes. Many people find it difficult to differentiate
between a class and a structure. Technically they both are regarded as the same in C++.

• Operators in C++

16 (07.01.2019, 11.01.2019, 14.01.2019)


• Assignment Operators:

• Bitwise Operator:

• Ternary Operator:

A ternary operator has the following form:

exp1 ? exp2 : exp3

The expression exp1 will be evaluated always. Execution of exp2 and exp3 depends on the outcome
of exp1. If the outcome of exp1 is non zero exp2 will be evaluated, otherwise exp3 will be evaluated.

17 (07.01.2019, 11.01.2019, 14.01.2019)


Complications:

Any side effects of exp1 will be evaluated and updated immediately before executing exp2 or exp3. In
other words, there is sequence point after the evaluation of condition in the ternary expression. If either
exp2 or exp3 have side effects, only one of them will be evaluated.

Return Type:

It is another interesting fact. The ternary operator has return type. The return type depends on exp2,
and convertibility of exp3 into exp2 as per usual\overloaded conversion rules. If they are not
convertible, the compiler throws an error. See the examples below,

The following program compiles without any error. The return type of ternary expression is expected
to be float (as that of exp2) and exp3 (i.e. literal zero – int type) is implicitly convertible to float.

• Some Special C++ Operators:

C++ has a rich set of operators. All C operators are valid in C++ also. In addition, C++ introduces
some new operators. We have already seen two such operators, namely, the insertion operator
<<, and the extraction operator >>. Other new operators are:

▪ :: Scope resolution operator


▪ ::* Pointer-to-member declarator
▪ ->* Pointer-to-member operator
▪ .* Pointer-to-member operator
▪ delete Memory release operator
▪ endl line feed operator
▪ new Memory allocation operator
▪ setw field width operator

In addition, C++ also allows us to provide new definitions to some of the built-in operators. That is,
we can give several meanings to an operator, depending upon the types of arguments used. This process
is known as operator overloading.

18 (07.01.2019, 11.01.2019, 14.01.2019)


▪ Scope Resolution Operator:

Like C. C++ is also a block-structured language. Blocks and scopes be used in constructing programs.
We know that the same variable name can be used to have different meanings in different blocks. The
scope of the variable extends from the point of its declaration till the end of the block containing the
declaration. A variable declared inside a block is said to be local to that block. Consider the following
segment of a program.
The two declarations of x refer to two different memory locations containing different values.
Statements in the second block cannot refer to the variable x declared in the first block, and vice versa.
Blocks in C++ are often nested. For example, the following style is common:

Block2 is contained in block 1. Note that a declaration in an inner block hicks a declaration of the same
variable in an outer block and, therefore, each declaration ofx causes it to refer to a different data
object. Within the inner block, the variable x will refer to the data object declared therein.
ln C, the global version DC u variable cannot be accessed from within the inner block. C++ resolves
this problem by introducing a new operator - :: called scope resolution operator. This can be used to
uncover a bidden variable. It takes the following form:
:: variable-name
This operator allows access to the global version of a variable. For example, ::count means the global
version of the variable count (and not the local variable declared in that block).

• Manipulators:

Manipulators are operators that are used to format the data display. The most commonly used
manipulators are endl and setw.
The endl manipulator, when used in an output statement. causes a Linefeed to be inserted. It has the
same effect as using the newline character "\n". For example, the statement
cout << 1111 = " << m << end l
19 (07.01.2019, 11.01.2019, 14.01.2019)
<< "n = " << n << end l
<< "p = " << p << end 1:
would cause three lines of output, one for each variable.

For the case of setw,


m • 2597
n • 14
p • 175
Here, the numbers are right-justified. This form of output is possible only if we can specify a common
field width for all the numbers and force them to be printed right-justified. The setw manipulator does
this job. It is used as follows:
cout << setw(S) << stMn << endl;
The manipulator setw(5) specifies a field width 5 for printing the value of the variable sum.

• Implicit Conversion (Typecasting),


• Explicit Conversion (Typecasting).

• Functions:

A function groups a number of program statements into a unit and gives it a name. This unit
can then be invoked from other parts of the program. The most important reason to use functions is to
aid in the conceptual organization of a program.
Dividing a program into functions is, one of the major principles of structured programming.
(However, object-oriented programming provides additional, more powerful ways to organize
programs.)
Another reason to use functions (and the reason they were invented, long ago) is to reduce program
size. Any sequence of instructions that appears in a program more than once is a candidate for being
made into a function. The function’s code is stored in only one place in memory, even though the
function is executed many times in the course of the program.

20 (07.01.2019, 11.01.2019, 14.01.2019)


When the function is called, the other statements in the function body are then executed and the control,
returns to the main program when the closing brace is encountered. C++ is no exception. Functions
continue to be the building blocks of C++ programs. In fact, C++ bas added many new features to
functions to make them more reliable and flexible.

21 (07.01.2019, 11.01.2019, 14.01.2019)


Each name (identifier) occurring in a program must be known to the compiler or it will cause an error
message. That means any names apart from keywords must be declared, i.e. introduced to the compiler,
before they are used.
Each time a variable or a function is defined it is also declared. But conversely, not every declaration
needs to be a definition. If we need to use a function that has already been introduced in a library, we
must declare the function but we do not need to redefine it.

• Declarations:
Each name (identifier) occurring in a program must be known to the compiler or it will cause an error
message. That means any names apart from keywords must be declared, i.e. introduced to the compiler,
before they are used.
Each time a variable or a function is defined it is also declared. But conversely, not every declaration
needs to be a definition. If we need to use a function that has already been introduced in a library, we
must declare the function but we do not need to redefine it.

• Main Function:

C does not specify any re-tum type for the main function which is the starting point for the execution
of a program. The definition of main() would look like this:
main()
{
//main program statements
This is perfectly valid because the main() in C does not return any value.
In C++, the main() returns a value of type int to the operating system. C++, therefore, explicitly defines
main () as matching one of the following prototypes:
Int main();
int main(int argc, char • argv0);
The functions that have a return value should use the return statement for termination.
Since the return type of functions is int by default. the keyword int in the main() header is optional.
Most C++ compilers will generate an error or warning if there is no return statement. Turbo C++ issues
the warning Function should return a value and then proceeds to compile the program. It is good
programming practice to actually return a value from main(). Many operating systems test the return
value (called exit value) to determine if there is any problem. The normal convention is that an exit
value of zero means the program ran successfully.

22 (07.01.2019, 11.01.2019, 14.01.2019)


Some functions require one or more arguments, which we pass when the function is called. Thus, an
argument is a value passed to a function. Arguments are specified between the opening and closing
parentheses when a function is called. For example, if MyFunc( ) requires an integer argument, then
the following calls MyFunc( ) with the value 2:
MyFunc(2);
When there are two or more arguments, they are separated by commas. In this book, the term argument
list will refer to comma-separated arguments. Remember, not all functions require arguments. When
no argument is needed, the parentheses are empty. A function can return a value to the calling code.
Not all functions return values, but many do. The value returned by a function can be assigned to a
variable in the calling code by placing the call to the function on the right side of an assignment
statement. For example, if MyFunc( ) returned a value, it could be called as shown here:
x = MyFunc(2);
This statement works as follows. First, MyFunc( ) is called. When it returns, its return value is assigned
to x. We can also use a call to a function in an expression. For example,
x = MyFunc(2) + 10;
In this case, the return value from MyFunc( ) is added to 10, and the result is assigned to x. In general,
whenever a function’s name is encountered in a statement, it is automatically called so that its return
value can be obtained. To review: an argument is a value passed into a function. A return value is data
that is passed back to the calling code.

• Declaration of Functions in Details:

A function has a name and a type, much like a variable. The function’s type is defined by its return
value, that is, the value the function passes back to the program. In addition, the type of arguments
required by a function is important. When a function is declared, the compiler must therefore be
provided with information on
■ the name and type of the function and
■ the type of each argument.
This is also referred to as the function prototype.
Examples: int topper(int);
double pow(double, double);
This informs the compiler that the function toupper() is of type int, i.e. its return value is of type int,
and it expects an argument of type int. The second function pow() is of type double and two arguments
of type double must be passed to the function when it is called. The types of the arguments may be
followed by names, however, the names are viewed as a comment only.
Examples: int toupper(int c);
double pow(double base, double exponent);

23 (07.01.2019, 11.01.2019, 14.01.2019)


From the compiler’s point of view, these prototypes are equivalent to the prototypes in the previous
example. Both junctions are standard junctions. Standard function prototypes do not need to be
declared, nor should they be, as they have already been declared in standard header files. If the header
file is included in the program’s source code by means of the #include directive, the function can be
used immediately.
Example: #include <cmath>
Following this directive, the mathematical standard functions, such as sin(), cos(), and pow(), are
available.

• Function Calls:

A function call is an expression of the same type as the function and whose value corresponds to the
return value. The return value is commonly passed to a suitable variable.
Example: y = pow( x, 3.0);
In this example the function pow()is first called using the arguments x and 3.0, and the result, the
power x3, is assigned to y. As the function call represents a value, other operations are also possible.
Thus, the function pow() can be used to perform calculations for double values.
Example: cout << 2.0 + pow( 5.0, x);
This expression first adds the number 2.0 to the return value of pow(5.0,x), then outputs the result
using cout. Any expression can be passed to a function as an argument, such as a constant or an
arithmetical expression. However, it is important that the types of the arguments correspond to those
expected by the function. The compiler refers to the prototype to check that the function has been
called correctly.
If the argument type does not match exactly to the type defined in the prototype, the compiler performs
type conversion, if possible.
Example: y = pow( x, 3); // also ok!
The value 3 of type int is passed to the function as a second argument. But since the function expects
a double value, the compiler will perform type conversion from int to double.
If a function is called with the wrong number of arguments, or if type conversion proves impossible,
the compiler generates an error message. This allows we to recognize and correct errors caused by
calling functions at the development stage instead of causing runtime errors.
Example: float x = pow(3.0 + 4.7); // Error!
The compiler recognizes that the number of arguments is incorrect. In addition, the compiler will issue
a warning, since a double, i.e. the return value of pow(), is assigned to a float type variable.

24 (07.01.2019, 11.01.2019, 14.01.2019)


• Functions without Return Values:

We can also write functions that perform a certain action but do not return a value to the function that
called them. The type void is available for functions of this type, which are also referred to as
procedures in other programming languages.
Example: void srand( unsigned int seed );
The standard function srand() initializes an algorithm that generates random numbers. Since the
function does not return a value, it is of type void. An unsigned value is passed to the function as an
argument to seed the random number generator. The value is used to create a series of random numbers.

• Functions without Arguments:

If a function does not expect an argument, the function prototype must be declared as void or the braces
following the function name must be left empty.
Example: int rand( void ); // or int rand();
The standard function rand() is called without any arguments and returns a random number between 0
and 32767. A series of random numbers can be generated by repeating the function call. Usage of
srand() and rand()
The function prototypes for srand() and rand() can be found in both the cstdlib and stdlib.h header
files.
Calling the function rand() without previously having called srand() creates the same sequence of
numbers as if the following statement would have been proceeded: srand(1);
If we want to avoid generating the same sequence of random numbers whenever the program is
executed, we must call srand() with a different value for the argument whenever the program is run.

A C++ Program to demonstrate a simple math function using inbuilt math library:
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
double number, squareRoot;
cout << "Enter a number: ";
cin >> number;

// sqrt() is a library function to calculate square root


squareRoot = sqrt(number);

25 (07.01.2019, 11.01.2019, 14.01.2019)


cout << "Square root of " << number << " = " << squareRoot;
return 0;
}

C++ program to User Defined Function for adding two integers. Make a function add() to add
integers and display sum in main() function.

#include <iostream>
using namespace std;
// Function prototype (declaration)
int add(int, int);

int main()
{
int num1, num2, sum;
cout<<"Enters two numbers to add: ";
cin >> num1 >> num2;

// Function call
sum = add(num1, num2);
cout << "Sum = " << sum;
return 0;
}

// Function definition
int add(int a, int b)
{
int add;
add = a + b;
return add; // return statement
}

___________________

26 (07.01.2019, 11.01.2019, 14.01.2019)

Das könnte Ihnen auch gefallen