Variables are places in memory that we name so that we can use it later. Again, we have with that idea of how a computer can only "do one thing at a time." So, when we ask the user "what is your name?" we would immediatly forget unless we store that name somewhere. So first, we gotta make the box where we store our information in. Then, we can put whatever we want in it.
However, with most languages we have also specify what KIND of box we want, numbers or words. Other languages, you dont need to specify the type at all where a box can contain anything. The reason the they want you to specify is so it can better optimize for certain operations. Also, it forces you to be a little bit safe with your own operations, like not trying to find the cosine of "hello".
Memory in the computer has addresses. They're in the form of hexadecimal numbers,
like
SO when we ask the computer "HAI i want to store an integer for later", the operating system says "OKIEZ you can haz this." And the operating will provide an address that points to a spot that has, oh lets say... 4 bytes, reserved. Every type of container can be different sizes for different purposes and these are called "data types."
At the moment, we can't really do too much with variables without operators, our next lesson.
Creating a varuable is simple.
data_type name_of_variable;
or
data_type name_of_variable = initial_value;
| Code | Use | Example |
| integer | Whole numbers | 321644 |
| float | numbers with decimal points | 3.641 |
| char | a single CHARacter | p |
| string | a bunch of characters | potato |
| bool | Boolean. true or false. | true |
#include <string> //need for "string"s to exist. Explained in another tutorial
#include <iostream>
using namespace std;
int main ()
{
int int_a; //integer with the name of int_a, no initial value
int int_b = 5; //integer, initialized with 5
float float_a = 3.22; //floating point number,
float float_b = -4.75; //floating point number,
char somecharacter = 'p'; //character, with letter 'p'
string str_a = "cheese"; //string, holds "cheese" (;
string str_b = "potato"; //string, holds "potato" (;
bool bol_a = true; //boolean, holding TRUE
//some math and stuff
int_a = -23; //give this a new value
int_b = int_a + int_b; //give this a new value of int_a + int_b
// ...and other operations with +-/*, outlined in next lesson.
//output everything!
cout << int_b << endl;
cout << int_a << endl;
cout << somecharacter << str_a << endl;
cout << float_b << " " << str_b << endl;
return 0;
}
28
-23
pcheese
-4.75 potato|