简体   繁体   中英

Variable Definition in C++, defining 3 variables?

I saw this line in a C++ code, I've just started C++ and I don't know what the line below does! I'm guessing its defining three variables lower, upper, and step that I don't have to initialize later? ie: lower =3, upper=4?

My Code in Question:

int lower, upper, step;

It is declaring 3 variables. It is not initializing any of them. It is equivalent to writing

int lower;
int upper;
int step;

All of these variables are declared, but none of them have been initialized.

If you wanted to initialize them, you would:

int lower = 0;
int upper = 0;
int step = 1;

The code above simply declares three variables. None of them are intialized. If you are doing object orientted c++ then the intialization would more or less take place in your constructor. But if not you can pretty much intialize later in the function or main body.

intialization would look like:

lower = 5; .....

Declaring these variables like so are necessary for inputting a value for the variable ie

cin>> lower; cin>> upper;

This is different then initializing them ie

int upper= 4;

The code simply declares the variables lower , upper , and step , reserving space in memory to allow data to be stored in these variables. Unless the variable is declared in the global scope, it does not assign any value to them. In C++, the values of such uninitialized variables are undefined ; in practice, this means that these variables will have values that are effectively random, determined simply by whatever leftover values exist in the memory locations reserved for these variables.

If you want to assign values to multiple variables as they are declared, you can put the assignments into the same line as the declaration:

int lower = 0, upper = 100, step = 1;

Alternatively, you can assign them values later, perhaps from an input statement:

int lower, upper, step;
cin >> lower >> upper >> step;
#include <iostream>

using namespace std; 
int main(){

//Declaration of variables; always includes a data type before the variable name.   
int lower;
int upper; 
int step;

//In this example, "int" is the data type. 

//Example of initialization: 
lower = 0; 
upper = 5; 
step = 1; 
}

//"lower" has been initialized to 0. 
//"upper" has been initialized to 5. 
//"step" has been initialized to 1. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM