In C++, you can declare multiple variables of the same type in a single statement. This helps make code cleaner and more efficient.
Declaring Multiple Variables
Instead of declaring variables separately, you can group them together using commas:
Example
C++
x
using namespace std;
int main() {
int speedA = 120, speedB = 150, speedC = 180; // Declaring multiple variables
cout << "Total combined speed: " << speedA + speedB + speedC << " km/h";
return 0;
}
Explanation:
- The variables
speedA
,speedB
, andspeedC
are all declared as integers (int
) in a single line. - Their values (
120
,150
,180
) are assigned immediately. - The sum of these values is printed using
cout
.
Assigning One Value to Multiple Variables
C++ also allows multiple variables to be assigned the same value in one step:
Example
C++
using namespace std;
int main() {
int bike1, bike2, bike3; // Declaring multiple variables
bike1 = bike2 = bike3 = 220; // Assigning the same value to all variables
cout << "Total combined bike performance rating: " << bike1 + bike2 + bike3;
return 0;
}
Explanation:
- The variables
bike1
,bike2
, andbike3
are all declared without immediate values. - They are later assigned the same value (
220
) in a single line. - The program outputs the sum of all three values.