There are a variety of variable types you can use in C++:
- int - Holds the value of an integer. Depending on the type, the value can range from as low as -2,147,483,648 to as high as 2,147,483,648
- float - Holds a value of 1.2e-38 to 3.4e38
- double - Holds a value of 2.2e-308 to 1.8e308
- char - Holds one character.
- bool - Holds a value of true or false (1 or 0)
Syntax of declaring variables:
All of the following are legal ways to declare variables in C++:unsigned short int shortstack = 128;
bool amitrue = false;
char what_letter_am_i = "Y";
float highm8 = 1.7777;
double imavaribale = 9.93;
When declaring variables, always be sure to set them to a value of something. If you can not set them to a value when you first declare them, then set them to 0 or null.
Having the user input a value of a variable with std::cin:
You can also have the user input the value of a variable by using the std::cin command which will pause the program until a value is input and the ENTER key is pressed. Two examples of this are below:
std::cin >> int anewvariable;
int anoldvariable = 0;
std::cin >> anoldvariable;
Constant Variables
In some cases in your programs, you will want to declare a variable whose value will never be changed. You can do this by placing the keyword "const" in from of your variable declaration. Several examples of this are below:
const unsigned short int avariable = 16;
const bool thisistrue = false;
const int myint = 8;
const char = "Q";
const unsigned short int avariable = 16;
const bool thisistrue = false;
const int myint = 8;
const char = "Q";
Quote:
ReplyDelete"All of the following are legal ways to declare variables in C++:
unsigned short int = 128; "
I believe you are missing the variable's name there. The format is always
'sign' 'length' 'type' 'name' = 'value'
right?
Correct Sir. Nice catch.
ReplyDelete