“Everyone in this country should learn how to program a computer... because it teaches you how to think.” - Steve Jobs
Starting in this lesson, we will be “getting our hands dirty”. Now, the lessons will be longer and contain more information. We will have whole chapters devoted to interesting projects, and we will discuss new C++11 features. Before we continue, I must say that most of what I’ve said in the previous tutorial is of vital importance. We will be moving forward now, and if you need a reminder about syntax, I suggest that you refer to previous chapters.
First, we will be discussing the “main()” function. This is, quite literally, the “main” part of your C++ application. This function (if you don’t know what a function is, hold on) tells our C++ compiler where to start. The Compiler will look for Main() and execute the code inside. This is why a deep understanding of main is so important.
Open up our previous project (Hello World!) in Visual Studio and look at the code:
You may have noticed the “int main()” line before the brackets and our main code. You might also have noticed the “return 0;” line also. Now, we will explain their significance.
This is where the compiler looks for the actual code to run. In this case, we print out “Hello World” and pause the system inside our main function.
As you may already have guessed, main() is a function. “What is a function?”, you may be asking. A function (more precisely, a Method) is a subroutine, or a piece of code within a larger program which performs a specific task. As you’ll see later on, you can have many functions in many different files. Main() is important because the code in main is what the compiler runs. If you didn’t have a main, the compiler would compile all of your code, however it wouldn’t run any of it.
Another interesting piece of code is the “int” before “main()” and our “return 0;” line. These are actually related, so we will discuss them both at the same time.
In C++, int stands for integer. The code “int main()” tells us that the “main()” function returns an integer. The return type (What type of value the function will return) of a function always comes before the name. An example would be:
As you can see, we have a return type, a function name (for our main() function, the function name is simply main), and a function parameter. Function parameters are values that are passed to a function. A function can have more than one function parameter, separated by a comma. In our “int main()” function, our return type is int, the name is main, and we take no arguments (thus empty parenthesis).
We also have the code “return 0;” inside our main function. As we’ve already established, the main() function returns an integer. We use the:
command to tell the function what to return. The function will return the “value” in “return value;”. This means that our main function returns 0, because the return statement of main() is “return 0;”.
Notice how zero is an integer. Functions can only return values that are of the return type specified right before the function name. If you tried to return something which wasn’t an integer (like 3.14, for example), you would get a compiler error.
Now that we understand the basics of functions and the main function, lets talk about Variables. Variables are the building blocks of programming. In their simplest terms, variables are a symbolic name attached to a value (the value can change, thus the term variable). To store values while we’re programming, we use variables.
If you’ve taken algebra, you may remember that there was variables in math also. In math, a variable was a symbol that represents a quality (Normally, the symbol was a letter and the quality was a number). You would have to find out the values of variables in Algebra, however. In programming, you assign variables values and use them.
If you want to declare a variable, you use:
The variable type is the type of the variable. A type is essentially a certain kind of value or variable. There are eight basic (or primitive) types:
These types are the building blocks of your application. As you can see, each variable takes up a certain number of bits has minimum / maximum values. We will now go over the variables.
Without further ado, let's see these variables in action. Edit your program so that it contains the following lines of code before our std::cout... statement:
Then, change our std::cout statement so that instead of printing out Hello World!, make it print out both number and firstLetterOfAlphabet. We can do this by deleting "Hello World!" and putting the names of the variables in it’s place. You must remember that since the variables are different types, we must separate them using the insertion operator (<). Make sure to keep our endl statement. Our code should now look like:
If you run our program now, you will see the values of number and firstLetterOfAlphabet printed out into the console right next to each other. These values are variables. Remember to always put the variable type before our name.
You can refer to the variables using their names. These variables are called local variables. This means that they are local to the function main. If you had another function and tried to use the number variable inside that function, you would get an error.
Variables are, well, variable. We can change their values many times. See this for yourself by adding more lines of code which change the value of number or firstLetterOfAlphabet (Or both) multiple times. As you will see, the last value that you assign to them is what is printed out.
It’s important to understand why variables are important: Many times in programming, you’ll be programming a problem which requires storing a value of some type. Variables store this value, and allow us to refer to the value using the variable’s name.
You can assign a variable a value when you create it or after. If we wanted to, we could create our number variable like so:
This is equivalent to the line:
Sometimes, you won’t get the value of a variable until late in a program. It is good practice, however, to declare(create) all of your variables at the beginning of your program (this makes it so that other people don’t have to search through your code to find variables). Giving your variables a value is called defining your variables. Make sure to always give your variables a value, even if it’s zero (for numbers) or a space (for characters). Giving a variable a value for the first time using the assignment operator (=) is called initializing the variable. It is good practice to always initialize your variables, because if you try to use them and you haven’t initialized them, you’ll get an Access Violation error (It is considered an access violation to read memory which hasn’t been initialized. This is because both uninitialized memory and all the memory your program uses are the same thing, and it is an error to read memory your program isn’t using.)
You can also create more than one variable of the same type at the same time. Examine the following code:
This code creates both an integer called number initialized to thirty, and an integer called otherNumber initialized to fifty-six. This allows us to accomplish the creation and initialization of many variables in one line of code. The variables must be the same type, however. We can’t use:
because of C++’s type-safety, and for clarity.
Operators are characters which allow us to perform operations on values. For now, we will go over the basic five operators for numeric (number) variables:
All of these operators take two operands: One on the left, and one on the right. their form is:
Let’s add two numbers and assign the value of their addition to another variable.
First, delete your firstLetterOfAlphabet variable and replace it with another integer variable called otherNumber. The value of this variable can be anything you would like. Then, create another variable called result and set it equal to the sum of number and otherNumber, like so:
Now, replace the printing of number and firstLetterOfAlphabet in our cout statement with the printing of only result. Our code should look like the following:
If you ran this code, you would see the number 57 printed to the screen followed by the console asking us to “press any key to continue...”.
Now, let’s go over the difference between a expression and a statement. So far, I’ve been using the term statement and command interchangeably. From now on, I will only use either expression or statement to describe our programs.
An expression is a small piece of code that can be evaluated to produce a result. An example would be 5 + 10. This can be evaluated to produce fifteen, so it is an expression. An expression’s exact definition is a combination of operators and operands.
A statement is different. Statements are complex pieces of code which normally end in a semicolon. They include calling functions (which we will discuss later on) and performing operations. They are the smallest units of execution in our program.
In C++11, we now have auto variables. For these variables, we don't have to specify a type. The compiler determines the type of the variable at compile time. To create an auto variable, simply put "auto" instead of the normal type of your variable. The compiler will find the variables type at compiler time.
In the above code, we create an auto variable and assign it to twenty-seven. auto variables must always be defined when they are declared. Because of this, we can't have:
Compilers look at line where we declare the variable when determining the type. If we don't assign the variable a value, it is impossible for the compiler to determine the type of the variable!
That is all for this lesson! See you again next time!
Cheers :)!
What is a variable?
Why are variables useful?
What does the multiplication operator look like?
What does it mean to initialize a variable?
How do we print out variables to the console?
Changelog:
Starting in this lesson, we will be “getting our hands dirty”. Now, the lessons will be longer and contain more information. We will have whole chapters devoted to interesting projects, and we will discuss new C++11 features. Before we continue, I must say that most of what I’ve said in the previous tutorial is of vital importance. We will be moving forward now, and if you need a reminder about syntax, I suggest that you refer to previous chapters.
First, we will be discussing the “main()” function. This is, quite literally, the “main” part of your C++ application. This function (if you don’t know what a function is, hold on) tells our C++ compiler where to start. The Compiler will look for Main() and execute the code inside. This is why a deep understanding of main is so important.
Open up our previous project (Hello World!) in Visual Studio and look at the code:
// Hello World!.cpp : Defines the entry point for the console application. // #include <iostream> int main() { std::cout << "Hello World!" << std::endl; std::cin.get(); return 0; }
You may have noticed the “int main()” line before the brackets and our main code. You might also have noticed the “return 0;” line also. Now, we will explain their significance.
This is where the compiler looks for the actual code to run. In this case, we print out “Hello World” and pause the system inside our main function.
As you may already have guessed, main() is a function. “What is a function?”, you may be asking. A function (more precisely, a Method) is a subroutine, or a piece of code within a larger program which performs a specific task. As you’ll see later on, you can have many functions in many different files. Main() is important because the code in main is what the compiler runs. If you didn’t have a main, the compiler would compile all of your code, however it wouldn’t run any of it.
Another interesting piece of code is the “int” before “main()” and our “return 0;” line. These are actually related, so we will discuss them both at the same time.
In C++, int stands for integer. The code “int main()” tells us that the “main()” function returns an integer. The return type (What type of value the function will return) of a function always comes before the name. An example would be:
returnType functionName(function Parameter) { Code! }
As you can see, we have a return type, a function name (for our main() function, the function name is simply main), and a function parameter. Function parameters are values that are passed to a function. A function can have more than one function parameter, separated by a comma. In our “int main()” function, our return type is int, the name is main, and we take no arguments (thus empty parenthesis).
We also have the code “return 0;” inside our main function. As we’ve already established, the main() function returns an integer. We use the:
return value;
command to tell the function what to return. The function will return the “value” in “return value;”. This means that our main function returns 0, because the return statement of main() is “return 0;”.
Notice how zero is an integer. Functions can only return values that are of the return type specified right before the function name. If you tried to return something which wasn’t an integer (like 3.14, for example), you would get a compiler error.
Now that we understand the basics of functions and the main function, lets talk about Variables. Variables are the building blocks of programming. In their simplest terms, variables are a symbolic name attached to a value (the value can change, thus the term variable). To store values while we’re programming, we use variables.
If you’ve taken algebra, you may remember that there was variables in math also. In math, a variable was a symbol that represents a quality (Normally, the symbol was a letter and the quality was a number). You would have to find out the values of variables in Algebra, however. In programming, you assign variables values and use them.
If you want to declare a variable, you use:
variableType variableName = variableValue;
The variable type is the type of the variable. A type is essentially a certain kind of value or variable. There are eight basic (or primitive) types:
These types are the building blocks of your application. As you can see, each variable takes up a certain number of bits has minimum / maximum values. We will now go over the variables.
bool (stands for boolean): Can be either true or false.
byte: Can contain any number between -127 and 127 (No Decimals).
short: Smaller (Shorter) version of integer (No Decimals).
char: Contains a single character. Can contain a large amount of different characters.
int: The basic Integer. Can contain a very large integer (No Decimals).
long: Largest type of integer. Can contain very small and high values (No Decimals).
float: Can contain very large floating-point numbers (Decimals).
double: Can contain extremely large floating-point numbers (Decimals).
Without further ado, let's see these variables in action. Edit your program so that it contains the following lines of code before our std::cout... statement:
int number = 27; char firstLetterOfAlphabet = 'a';
Then, change our std::cout statement so that instead of printing out Hello World!, make it print out both number and firstLetterOfAlphabet. We can do this by deleting "Hello World!" and putting the names of the variables in it’s place. You must remember that since the variables are different types, we must separate them using the insertion operator (<). Make sure to keep our endl statement. Our code should now look like:
// Hello World!.cpp : Defines the entry point for the console application. // #include <iostream> int main() { int number = 27; char firstLetterOfAlphabet = 'a'; std::cout << number << firstLetterOfAlphabet << std::endl; std::cin.get(); return 0; }
If you run our program now, you will see the values of number and firstLetterOfAlphabet printed out into the console right next to each other. These values are variables. Remember to always put the variable type before our name.
You can refer to the variables using their names. These variables are called local variables. This means that they are local to the function main. If you had another function and tried to use the number variable inside that function, you would get an error.
Variables are, well, variable. We can change their values many times. See this for yourself by adding more lines of code which change the value of number or firstLetterOfAlphabet (Or both) multiple times. As you will see, the last value that you assign to them is what is printed out.
It’s important to understand why variables are important: Many times in programming, you’ll be programming a problem which requires storing a value of some type. Variables store this value, and allow us to refer to the value using the variable’s name.
You can assign a variable a value when you create it or after. If we wanted to, we could create our number variable like so:
int number; number = 27;
This is equivalent to the line:
int number = 27;
Sometimes, you won’t get the value of a variable until late in a program. It is good practice, however, to declare(create) all of your variables at the beginning of your program (this makes it so that other people don’t have to search through your code to find variables). Giving your variables a value is called defining your variables. Make sure to always give your variables a value, even if it’s zero (for numbers) or a space (for characters). Giving a variable a value for the first time using the assignment operator (=) is called initializing the variable. It is good practice to always initialize your variables, because if you try to use them and you haven’t initialized them, you’ll get an Access Violation error (It is considered an access violation to read memory which hasn’t been initialized. This is because both uninitialized memory and all the memory your program uses are the same thing, and it is an error to read memory your program isn’t using.)
You can also create more than one variable of the same type at the same time. Examine the following code:
int number = 30, otherNumber = 56;
This code creates both an integer called number initialized to thirty, and an integer called otherNumber initialized to fifty-six. This allows us to accomplish the creation and initialization of many variables in one line of code. The variables must be the same type, however. We can’t use:
int number = 30, char character = 'a';
because of C++’s type-safety, and for clarity.
Operators
Operators are characters which allow us to perform operations on values. For now, we will go over the basic five operators for numeric (number) variables:
+ adds two numbers - subtracts two numbers * multiplies two numbers / divides two numbers % gives the remainder of two numbers
All of these operators take two operands: One on the left, and one on the right. their form is:
op1 (operator) op2;
Let’s add two numbers and assign the value of their addition to another variable.
First, delete your firstLetterOfAlphabet variable and replace it with another integer variable called otherNumber. The value of this variable can be anything you would like. Then, create another variable called result and set it equal to the sum of number and otherNumber, like so:
number = 27; otherNumber = 30; result = number + otherNumber;
Now, replace the printing of number and firstLetterOfAlphabet in our cout statement with the printing of only result. Our code should look like the following:
// Hello World!.cpp : Defines the entry point for the console application. // #include <iostream> int main() { int number = 27; int otherNumber = 30; int result = number + otherNumber; std::cout << result << std::endl; std::cin.get(); return 0; }
If you ran this code, you would see the number 57 printed to the screen followed by the console asking us to “press any key to continue...”.
Now, let’s go over the difference between a expression and a statement. So far, I’ve been using the term statement and command interchangeably. From now on, I will only use either expression or statement to describe our programs.
An expression is a small piece of code that can be evaluated to produce a result. An example would be 5 + 10. This can be evaluated to produce fifteen, so it is an expression. An expression’s exact definition is a combination of operators and operands.
A statement is different. Statements are complex pieces of code which normally end in a semicolon. They include calling functions (which we will discuss later on) and performing operations. They are the smallest units of execution in our program.
In C++11, we now have auto variables. For these variables, we don't have to specify a type. The compiler determines the type of the variable at compile time. To create an auto variable, simply put "auto" instead of the normal type of your variable. The compiler will find the variables type at compiler time.
auto number = 27;
In the above code, we create an auto variable and assign it to twenty-seven. auto variables must always be defined when they are declared. Because of this, we can't have:
auto number; number = 17;
Compilers look at line where we declare the variable when determining the type. If we don't assign the variable a value, it is impossible for the compiler to determine the type of the variable!
That is all for this lesson! See you again next time!
Cheers :)!
Questions
What is a variable?
Answer: A symbol attached to a value
Why are variables useful?
Answer: They allow us to store data
What does the multiplication operator look like?
Answer: *
What does it mean to initialize a variable?
Answer: to assign it a value for the first time
How do we print out variables to the console?
Answer: Using cout, separating the variables we would like to print out with the insertion operator
Coming in next tutorial: Console Input and Output!
Changelog:
- Fixed formatting!
- Synchronized Code!