Explain about references in C++

Estudies4you
Q31. Explain about references in C++
Answer:

Reference
Reference is a substitute of an object. It acts as an implicit pointer. A variable which provides an alternative name for a previously defined variable is called as a reference variable. The syntax to declare a reference variable is as shown below,
datatype &reference = variable;
The token ‘&’ is added to the name of a returned type which means that the operator (or function) returns a reference.
Here, the token ‘&’ is known as the ‘reference declarator.

Example
Consider two variables x and y. Suppose variable ‘y’ is a reference variable to ‘x’ then the variable y and x are interchangeable for representing that variable.
int x = 10;
int &y = x; //y is initialized
In the above example, x is’a variable of integer type with a value 10. While the variable y is the alias of x i.e., y is declared to represent the x variable. Therefore, both the variables indicate the same value 10. And the output statement of both the variables (cout << x; and cout << y;) prints the same integer value 10.
The statement x = x + 10; will change value of both x and y to 20. In the same way y= 0 will also change the value of both the variable to 0.
In order to bound the reference to an object, the reference variable must be initialized at the time of its declaration.
However, reference initialization is completely different from reference assignment. No operation can operate on a reference despite of its appearance.

Program
#include<iostream.h> .
#include<conio.h>
int main()
{
double x;
double &y = x; // y is a double reference
clrscr();
x = 20.5;
cout<<“The value of variable x:"’<<x <<“\n”;
cout<<"The value of reference variable x: "<< y<<“\n”;
getch( );
return 0;
}

Output:


Q32. Discuss about flow control statements.
Answer:

Flow Control Statements
A program consists of a list of statements which will be executed in the given order. The execution order of the statements is generally referred to as flow of control. Thus, these statements are called as flow control statements.

Flow control statements are of three types. They are
  1. Conditional Control Statements
  2. Loop control statements
  3. Jump statements.
1. Conditional Control Statements

2. Loop Control Statements

3. Jump Statements
To Top