Functions, For, Labels & Pointers!
Since we're nearing the end of the tutorial for beginners, and the next things we are going to talk about are pretty confusing to most people who are new to them, I decided to give real examples of them in action.
I strongly advise you are well versed in what my tutorials covered so far before proceeding.
This lesson will cover:
- The structure of a program
- The "for" loop
- Labels
- Functions (with examples)
- Pointers (with examples)
Since this lesson will also include details about design we must talk about the structure of a program.
The structure of a program
While I have delayed talking about this because you wouldn't need it up to now and most likely forget about it, every program follows a structure.
And here you will finally begin to understand the basics of programming.
A very basic representation would be:
However for me at least it doesn't tell me squat.
So in order to make a more detailed representation that can also be understood I will begin explaining it in full detail.
Note: we are not going to talk about classes yet.
First off in any programs you've noticed that we include the headers(#include <iostream>
)
What I didn't tell you was that you can also declare Global Variables.
After which you add the functions before the main().
Not understanding where I'm getting at?
C++ Reads from top to bottom.
For example:
cout << i;
int i = 20;
Wouldn't ever work, because i is not declared yet.
Always be very cautious about this because when we talk about functions there may come a time when you want to use functions between them.
The following is an example of how a program should be neatly ordered:
#include <iostream>//Headers you will find others such as conio.h or even make your own, either way they all come first.
using namespace std;//Global Declaration
int Gvariable = 100;//Global Declaration//Global Variable
int a()//Function
{
//I can be accessed by both b & main
//I can not access b or main
//I can access Gvariable
}
int b()//Function
{
//I can be accesed by main only.
//I can not access main
//I can access GVariable and a()
}
int main()//Main function/Point of execution/Where the program starts
{
//I can't be accessed by a or b.
//I can access Gvariable, a and b
}
//There is one common rule amongst them in fact it's the same rule everywhere.
//The rule everything shares is: I can access everything above me with one exception! the variables inside the functions.
All of the above is very important, treat it as such or pay severely later on.
While all that seems very simple, when you're developing larger programs you might find yourself at a point where you realize that there's also the most important part of programming, which is designing.
The for loop
I regret to say that loops get a lot more complicated.
Too complicated to cover them all in the previous tutorial.
And this is all for good reason, but it's easier to just include one more at a time than to try understanding them all at once.
The for statement is a little trickier than while, but if you follow this rule it will always be simple in reality.
The for loop is designed to iterate a number of times. Its syntax is:
for (initialization; condition; increase/decrease) statement;
In this case I will ask you to remember the countdown example in the previous tutorial.
And compare these two.
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)//We put initialization, condition & action(decrement) here.
{ //Already a lot less cluttered right?
cout << n << ", ";//This seems like a better way doesn't it?
}
cout << "I've finished counting down to 0.";
}
Now this is how you should actually do a countdown
And that is also why I put the while(exit != true) example.
for countdowns and structures such as decrements & increments you should use the for loop.
Alright, now that's not all the for loop can do, yet we are not going to go into that in the beginners tutorial
The Label, Or Goto statement.
The label is very simple to understand, except a word of caution. I've found that I prefer not to ever use it, because the label is basically a loop that doesn't require any conditions.
Here's a proper example of how you could use loop&goto:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string i;
mylabel://Start of the loop
cout << "What word would you like me to print?\n"
<< "Input: ";
cin >> i;
system("cls");
if(i == "exit") //This is how you would end such a loop.
{
system("cls");
cout << "Ending the loop!\n";
}
else //Exit not inputted, continuing program.
{
cout << "You've asked me to print:\n" << i
<< "\nType exit when you want this loop to finish\n";
system("pause");
system("cls");
goto mylabel;//Loop trigger
}
cout << "The loop has ended!";
return 0;
}
While you can use the "break & continue" statements in while & for loops, you can't use these here to break a label-goto statement, hence the label name.
It's a jump in the program, therefor proper conditioning needs to be made.
I personally avoid using it, It looks to disorganized for me, but you might like it and it's there so it's your call!
Functions
We're finally getting to the more advanced part, from here on now you will start having to design your programs, or.. since this is the new trend we'll call them, Apps.
Let's start off with the simplest example I can give you.
#include <iostream>
#include <string>
using namespace std;
int message()
{
cout << "The message() function prints this string\n";
system("pause");
}
int main()
{
message();
return 0;
}
Here's even a neat little trick I loved doing when learning how to program, I hated typing system("pause") & system("cls") it was just plain too much text and too boring and sometimes I mistyped one letter simply said, it was annoying. So I used functions to shorten them like this:
#include <iostream>
using namespace std;
int cls()
{
system("pause");
}
int pz()
{
system("pause");
}
int main()
{
cout << "Hello, look at that awesome shortcut!\n";
pz();
cls();
cout << "Neat little trick huh?\n";
pz();
return 0;
}
Functions are awesome!
However they too have a few rules, you see there are variables that are called public/global because everyone can access them, and there are variables that are private because only their "father" can access them. I'm going to make a sort of schematic down here:
#include <iostream>
using namespace std;
int myglobalvar // Global variable can be used by everyone (A, B, & MAIN)
int A()
{
int myprivatevar1; //Private variable, can only be used by A
}
int B()
{
int myprivatevar2; //Private variable, can only be used by B
}
int main()
{
int myprivatevar3; //Private variable can only be used by main
return 0;
}
What?! But that limits us so much. Indeed, it would set technology back decades, but that's not the case, I haven't finished yet!
Here's another way, the real way, to use functions.
#include <iostream>
using namespace std;
int add(int a, int b)
{
int result;
result = a + b;
return result;
}
int main()
{
int firstnum, secondnum;
cout << "Enter the first number to add:";
cin >> firstnum;
cout << "Enter the second number to add: ";
cin >> secondnum;
cout << "The result is:" << add(firstnum,secondnum) << endl;
system("pause");
return 0;
}
That gives room for a lot more posibilites right?
Of course it does!
Let's try using something other than numbers so you can understand it easier.
#include <iostream>
#include <string>
using namespace std;
int awesomechicks()
{
cout << "Name Age Phone\n"
<< "Amy ? 023013213\n"
<< "Jennie 21 172423221\n"
<< "Right hand 99 123421421\n";
}
string auth(string username, string password)//Pay attention to this. Notice the string, because we're going to input strings to it.
{
if(username == "admin" && password == "pimp")
{
cout << "Successfully authenticated!\n";
system("pause");
system("cls");
awesomechicks();
}
else
{
cout << "Invalid username or password!\nThe program will now close\n";
}
}
int main()
{
string u, p;
cout << "Enter your username:\n";
cin >> u;
cout << "Enter your password:\n";
cin >> p;
auth(u,p); //Notice the cool thing about this?
system("pause");
}
//Now as much as this was to show you how functions work, don't do it this way, it's faulty.
Well that's a neat organization right?
Of course, this is just an example so your imagination can get going with them.
However That example is a very bad way of doing things, here's a proper example:
#include <iostream>
#include <string>
using namespace std;
int mychicks()
{
system("cls");
cout << "Name Age Phone\n"
<< "Amy ? 023013213\n"
<< "Jennie 21 172423221\n"
<< "Right hand 99 123421421\n";
}
string auth(string username, string password)//Pay attention to this. Notice the string, because we're going to input strings to it.
{
if(username == "admin" && password == "pimp")
{
return "Success!";//This function is based on a string, therefor you should return a string.
//If you want to return a number(int), go back to tutorial 2.
}
else
{
return "Failure!";//Remember that this is what the function returns.
}
}
int main()
{
string u, p;
cout << "Enter your username:\n";
cin >> u;
cout << "Enter your password:\n";
cin >> p;
if(auth(u,p) == "Success!")//The function auth(u,p) returns what we told it to
{ //In this case, "Success!" *do notice the exclamation mark, that's included too.
cout << "Success!\n"; //You could do cout << auth(u,p) << endl; It would be the same thing
system("pause");
mychicks();
}
else if(auth(u,p) == "Failure!")//The function auth(u,p) returns what we told it to
{ //In this case, "Failure!"
cout << "Complete and utter " << auth(u,p) << endl; //We could've done it to success too!
}
else
{
cout << "Something went horribly wrong, neither success nor failure were returned.";
//Take it from me, this method can sometimes save a lot of hours when something goes wrong
//It's called error-catching and the more you have the better! Because when hell breaks loose,
//You will only have yourself to blame.
}
system("pause");
}
Pointers
If you loved pointers before, now you're probably going to hate them.
A lot of people are confused when it comes to pointers. So after showing you the syntax and simple usage.
I'll come up with a few examples to make them easier, or at least try...
BASICS FIRST
Think of pointers as exactly what they are named like.
They point to stuff.
For example my pointervar, can either point to var a or var b.
I bet you are asking yourself: Okay.. why the hell do I need that?
Besides organizing?
Sometimes they can rescue you, other times they save a lot of time by allowing you to work less.
So here's how a pointer would work:
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int *pointer;
pointer = &a; // Point to a's address.
cout << pointer; //Print a's address.
cout << *pointer; //Print a's Value
}
Now, I want to ask you to pay attention and take note that I said it points to a's address..
It's more important than you think, and later I will show you why ^_^.
Now let's make a few examples of how they work so you grasp their concept even more.
Again, don't skip pointers they are life savers and they are very useful, even though you don't realise it yet.
Pointer random example 1
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 3;
int *p1 = &a;
int *p2 = &b;
int result = *p1 + *p2;
cout << result << endl;
system("pause");
return 0;
}
Pointer random example 2 Strings are trickier :)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a = "Hello";
string b = "World";
string *p;
string message;
p = &a;//notice I'm not using *.
message = *p;//Notice this time I used *p not p.
p = &b;//notice I'm not using *.
message = message + " " + *p; //notice I am using *, I want the value of the address that p points to.
cout << message << endl;
system("pause");
return 0;
}
Personal confession, I hate pointers. Don't be sad if you hate them too, but now let's show a very simple example as to why they "could" be useful.
#include <iostream>
#include <string>
using namespace std;
int *p;
string function(int a,int b)
{
int result; //Private variable;
result = a + b;
p = &result;
return "Function Resulted in: ";
}
int main()
{
int x = 2;
int y = 3;
string message = function(x,y);
int result = *p;
cout << message << result << endl;
return 0;
}
You're probably thinking: WTF!? wait! You accessed a variable from inside a function from main!?
But how? Didn't you say that's impossible?
Not if you point directly to the memory of it, and take that value through a global pointer there's nothing to stop you. main() by itself has no access to function. But the pointer was adressed inside the function's private variables. In fact pointers can be used anywhere within the program as long as it's designed properly
Think of this as using pointers as an intermediary.
However, Already we are talking design here there are rules to follow if you don't want to end up like these guys
First, the function must be executed, (It was executed when I asigned it to message)
Why? Because the memory needs to be created before the pointer can be assigned,
otherwise your program will because there will be no memory for that pointer to access when you call it.
If the function has not been executed yet, no such memory exists.(after all you can use the function as many times as you want)
Only after that can you assign the pointer.
When you're doing a large project. I strongly suggest you design it first, use schemes draw them on a blackboard use paintms I don't care.
Design ahead or you will have hell to pay.
That concludes today's lesson, I hope it helped you all and please don't forget to upvote & follow if this tutorial was useful to you!
Everything I've written here is my own personal work.
The header, as always, is of my own design.
List of images that are public domain:
Structure of a program
Architectural disaster
Arhitectural disaster2
BOOM
Pointy
Goto
functions
Is there something you guys don't like?
Tell me in the comments, I'll try making it better!
I'm always open to constructive criticism or even corrections, I know I make mistakes too!
Very good post!
Thank you :)