2.5k views
0 votes
I want to declare a variable v, and a reference r, and have the reference refer to the variable. Which statement accomplishes this?

A) int v; int& r = v;
B) int& r = v; int v;
C) int v; int r = &v;
D) int r = &v;

User LeMiz
by
8.4k points

1 Answer

4 votes

Final answer:

The correct statement to declare a variable 'v' and a reference 'r' would be 'int v; int& r = v;'. It is important that the variable is declared before the reference, and a reference, not the variable's address, is assigned.

Step-by-step explanation:

To declare a variable v, and a reference r that refers to the variable v, the correct statement is:

A) int v; int& r = v;

In C++ programming, you first declare the variable, and then you can declare a reference to it. Option A does this in the correct order. It is vital that the variable is declared before you try to create a reference to it, making the other options incorrect. For example, option B attempts to declare the reference before the variable, which would result in a compilation error. Option C and D incorrectly attempt to assign the address of the variable to an integer rather than creating a reference.

User Piotr Rogowski
by
7.7k points