A computer program is a sequence of instructions that tell the computer what to do.
Statements and expressions
The most common type of instruction in a program is the statement. A statement in C++ is the smallest independent unit in the language. In human language, it is analogous to a sentence. We write sentences in order to convey an idea. In C++, we write statements in order to convey to the compiler that we want to perform a task. Statements in C++ are terminated by a semicolon.
There are many different kinds of statements in C++. The following are some of the most common types of simple statements:
int x; x = 5; cout << x;
int x is a declaration statement. It tells the compiler that x is a variable. All variables in a program must be declared before they are used. We will talk more about variables shortly.
x = 5 is an assignment statement. It assigns a value (5) to a variable (x).
cout << x; is an output statement. It outputs the value of x (which we set to 5 in the previous statement) to the screen.
The compiler is also capable of resolving expressions. An expression is an mathematical entity that evaluates to a value. For example, in math, the expression 2+3 evaluates to the value 5. Expressions can involve values (such as 2), variables (such as x), operators (such as +) and functions (which return an output value based on some input value). They can be singular (such as 2, or x), or compound (such as 2+3, 2+x, x+y, or (2+x)*(y-3)).
For example, the statement x = 2 + 3; is a valid assignment statement. The expression 2+3 evaluates to the value of 5. This value of 5 is then assigned to x.
Functions
In C++, statements are typically grouped into units called functions. A function is a collection of statements that executes sequentially. Every C++ program must contain a special function called main(). When the C++ program is run, execution starts with the first statement inside of main(). Functions are typically written to do a very specific job. For example, a function named Max() might contain statements that figures out which of two numbers is larger. A function named CalculateGrade() might calculate a student’s grade. We will talk more about functions later.
Libraries
Libraries are groups of functions that have been “packaged up” for reuse in many different programs. The core C++ language is actually very small and minimalistic — however, C++ comes with a bunch of libraries, known as the C++ standard libraries, that provide programmers with lots of extra functionality. For example, the iostream library contains functions for doing input and output. During the link stage of the compilation process, the libraries from the C++ standard library are the runtime support libraries that are linked into the program (this will be discussed further in lesson 1.4).
Taking a look at a sample program
Now that you have a brief understanding of what statements, functions, and libraries are, let’s look at a simple hello world program.
Consider our hello world program:
#include <iostream>
int main()
{
using namespace std;
cout << "Hello world!" << endl;
return 0;
}
Line 1 is a special type of statement called a preprocessor directive. Preprocessor directives tell the compiler to perform a special task. In this case, we are telling the compiler that we would like to use the iostream library. The iostream library contains code that tells the compiler what cout and endl do. In other words, we need to include the iostream library in order to write to the screen.
Line 3 declares the main() function, which as you learned above, is mandatory. Every program must have a main() function.
Lines 4 and 8 tell the compiler which lines are part of the main function. Everything between the opening curly brace on line 4 and the closing curly brace on line 8 is considered part of the main() function.
Line 5 is our first statement (you can tell it’s a statement because it ends with a semicolon). As you learned in the explanation for line 1, cout and endl live inside the iostream library. However, within iostream, they live inside a special compartment named std (short for standard). This using statement tells the compiler to look inside a compartment named std if it can’t find cout or endl defined anywhere else. In other words, this statement is also necessary so the compiler can find cout and endl, which we use on line 6.
Line 6 is our output statement. Cout is a special object that represents the console/screen. The << symbol is an operator (much like + is an operator) called the output operator. Cout understands that anything sent to it via the << operator should be printed on the screen. Endl is a special symbol that moves the cursor to the next line.
Line 7 is a new type of statement, called a return statement. When an executable program finishes running, it sends a value to the operating system that indicates whether it was run successfully or not. The return value of main() is used for this purpose. This particular return statement returns the value of 0 to the operating system, which means “everything went okay!”. Non-zero numbers are typically used to indicate that something went wrong, and the program had to abort. We will discuss return statements in more detail when we discuss functions.
Conclusion
All of the programs we write will follow this template, or a variation on it. We will discuss each of the lines above in more detail in the upcoming sections.
Quiz
The following quiz is meant to reinforce your understanding of the material presented above.
1) What is the difference between a statement and an expression?
2) What is the difference between a function and a library?
3) What symbol do statements in C++ end with?
Quiz Answers
To see these answers, select the area below with your mouse.
1.2 — Comments
|
Index
|
0.7 — A few common C++ problems
|
1.2 — Comments
Index
0.7 — A few common C++ problems
[...] the section Introduction to programming, we had defined an expression as “A mathematical entity that evaluates to a value”. [...]
I don’t know if you have noticed, but all the line numbers are off by one 6 should be 7 and so on.
I think?
Yes, it is..
But, i think you are not here to point out errors..
i think you should learn.. rather than concentrating on to the errors on the page..
You can’t just simply walk into mordor!
You have my axe.
GIMME MY MONEH!
Nope, Anthony, make sure u added the spaces where they are in the code presented here, even though that is all just semantics, developing good habits with whitespace will be essential. (whitespace)- The space in between all your code that you see but the compiler doesnt see.
thanx
IMO, the wording of “During the link stage of the compilation process, the libraries from the C++ standard library are the runtime support libraries that are linked into the program.” is confusing, because we haven’t yet been told what “runtime support libraries” are exactly.
Also, a typo in the sentence: “Cout understands that anything send to it via the…..” – “send” should be “sent“.
Al:
You have the line numbers wrong.
Also you miss 0.7 at the top going back and forth:
« 0.6 — Compiling your first program | Home | Tiga 1.0.2 widget fix for WordPress 2.2 »
Æ’g
That is a known issue at this time. :) Those navigation links are generated automatically by my wordpress theme in the order I wrote the articles. However, I didn’t write all of the articles in order, so some of the links are out of order. I will have to fix them manually at some point in the future.
Al
I did not make it clear the line numbers of the program do not match your coments.
Æ’g
The line numbers look fine to me.
I see this:
Are you seeing something different?
It displays properly in Firefox browser but incorrectly (One Line off) in Internet Explorer.
Oh wow, thanks for letting me know. I hadn’t even noticed when I looked at the page previously in IE.
This is a great tutorial site but you really need a “next lesson” single click. kind of bugs me to have to go back to the home screen, remember what I clicked last etc…
Just a thought..
MosFetMan
This is planned for the very near future. Thanks for your thoughts!
[...] Alex: This is planned for the very near future. Thanks for your thoughts! Archives [...]
[...] 1.1 — Structure of a program [...]
Thanks for this part of the tutorial. I found this section really helpful.
hey man very nice though you wrote ” would like to use the iosteam library.” in the first paragraph after
“Taking a look at a sample program”
I’m not sure what the problem is with that. Am I missing something? :)
iosteam should be iostream. It is missing an “r”.
[ Wow, I can't believe I didn't see that. Fixed now! Thanks all. -Alex ]
using namespace std; is in the wrong line
it should be in the main header before int main( )
I’m not sure if it differentiates between C++ Compilers or not but I’m using Visual C++ and my program will not compile unless the using namespace std; is outside of the main function
is an expression a type of statement?
I’m not quite sure how to answer that.
In most cases, and expression is PART of a statement. For example:
“2 + 3″ is an expression that evaluates to 5. x = 2 + 3 is an assignment statement that assigns the result of evaluation 2 + 3 to variable x.
It is possible to have a statement that consists only of an expression. For example, the following is allowed:
This expression evaluates to 5, but since the result is not used anywhere it is just discarded.
if “cout < < “Hello world!” << endl;” is a statement and “<<” is an operator what is “cout” a command?
cout is actually a variable that is predefined by the standard library. The variable is of type ostream, which is a class. Classes allow you to define your own variable types. We cover classes in more detail in chapter 8.
if “cout” is an object of a class, then who actually does instantiate it ? we do not create this instance in our code. Is this object created before the actual code is executed ?
this one with
is not worcking or at least i cant make it worck
What error message is it giving you? Don’t forget to #include if you’re using a microsoft compiler.
Out of date? O_o How do you mean? All the commands the code uses aren’t depreciated.
Just not sure what you meant by that.
That happened with me before when using Visual Basic C++ 2010 Professional.
I’m not sure how I’ve fixed it but at I started a debug and did some other stuff
and then it suddenly stopped complaining about it.
it is very usefull i m very week in programing can i do it through this site
I have Visual C++ 2005 Express Edition,
but my lines aren’t numbered. Why?
This article has some helpful information for turning on line numbering in Visual Studio 2005.
And to add in a little Open Source plug (I swear I’m not being paid), Code::Blocks turns on line numbering by default.
Hum i sure to have one or two knowledges…love u keep it up.
this is just stupid, Why learn C++ when you can learn something that will help you in life, some some stupid illusion on a screen created by little nerds from silicon town, or whats it call, shit guy grow up and be man, damn it.
dude your an idiot I’m not sure if you like video games or not but do you like Halo? Halo was most likely written in C++. Visual C++ as the Compiler DirectX to load 3D Models and Textures Maya or 3D Studio Max to create those 3D Models Photoshop or ZBrush to create those textures etc the world as we know it would not be the way it is today without programming so stop being so stupid
Look at your friggin’ self, you associate your post with a Videogames that isn’t all that great to the world: Halo.
Why do 13 year old males considered to be the best thing in the world? It is not, we all have different friggin values on something else. Sadly I have to use the word “opinion” because the only word you 13 year old are going to here everyday when you don’t shut your mouth.
What gave you the idea to bring up Halo in your comment?
Why must the internet be littered with 13 year old males? Why?
Leading Man, we need people just like you. Because who’s going to take my order at a fast food joint? Or who’s going to keep my fries hot?
Why waste your time on this tutorial to post inapropriate comments and troll this website when you can be doing other “useful shit”?
Do you not see that the internet was created from programming? That videogames were created from Programming? GPS’s, Cell Phones, hell even some Operating Systems for computers?
leading man is right grow some balls man ( Pokemon Gotta catch them all Pokemon ) You fags should play that manly game
and for you your an idiot too for going along with your idiot friend up there C++ is the most widely used language in the world while people out there are programming software in C++ and earning 85,000 a year you will probably still be working at McDonalds earning minimum wage while living in your moms basement
i love you leading man
Shut the fu*k up mike, you know ill own you at golf, bitch. suck it!!!!
8===================================D
lmao dam you got me but is yours that long wow mine is wayyyyyyyyyyyyyyyyyyyyyyyyyyyyy bigger then that piece of sh*T
The Friendship Ball
A ball
is a circle, No
beginning, no end.
It keeps us together Like
our Circle of Friends But the
treasure inside for you to see
is the treasure of friendship
You’ve granted to me.
Today I pass the
friendship ball
to you.
Pass it on to someone who is a friend to you.
lmao ill pass it to your mom
my moms dead.
lmao sorry well ill do your stepmom
Very well, incestial f***.
mike, TELL ME HOW AM I SAPPOSE TO LIVVVVVVVVVVVVEEEEEEEE WITH OUT YOU!!! NOW THAT I BEEN LOVING YOU SO LOOOOONNNNNG< TELL ME HOW AM I SAPPOSE TO LLLLLLLLLLLLLLLLLLIIIIIIIIIIIIIIIIIIIIIIVVVVVVVVVVVVVVVVVVVVVEEEEEEEEEEEEEEEE WITH OUT YOU! WHEN ALL I BEEN LIVING FOR IS GONE…………
i want knowwwwwwwwwwwwwwwwwwwwwwww what loveeeeeeeee isssssssssssss>>>>>>>>> i want you to showwww meeeeeeeeeee >>>>>>>>>>>
meet me on conway on 8 mile road so we can rape
i know you love me, I show you what love is <3 let be togeter FOREVER!!!!
but im married with Carrot Top how do i tell him its over :( he has a hugh Co*k i dont wann leave it
………………………………………… skew you
hey guys
im gay leading man is my wife
hmmmmm… fancy that, but I must confess that I am indeed stright, I simpley just dont swing that way mike, Though I must admit that we had a good jest , but never the less, it was simply a Jest. My regards to you and your firend ….carrot. after all I am the leading man and you know what they say about the leading man, He never dies.
Hello mister…what the hell u both r doing here.if u don’t want to learn, go somewhere else. But please don’t do this rubbish here!
Thanks Pramod . . . I only carried on reading this thread to see if someone gave them a clip on the ear : D . . .I’ll use this comment to Thank you aswell Alex, (to avoid spamming your page) You prob dont sift through this early section -I can see you have tweaked the site and above content already .. But hopes you do pal, Good work m8 ..I’m generaly too busy to get back to learning but this does speak to me I’ll be here for a while now : ) Again, legend like your effort : D
Is there any explanation about the structure of Standard Template Library (STL)in this site?
Instead of you two flirting on here, why don’t you take it somewhere private.
I don’t understand what they’re even doing here =-_-=
Dont mind them guys…u know fools are always making noise and letting others to know that they are really stupid from birth. They know here is a discussing board for programming learners.And still they came in just to be noticed. Time will come knocking at their doors soon..do not worry.
in the first line if we use </.h>
then the program work otherwise there will be an error
Wow ur teaching or tutorial here is much better than my teacher. I’m currently studying engineering with c++ as a module but till now i nvr knew the true meaning of 0 at the return 0.
It would be good if you could explain the difference between functions and methods.
Can you make a PDF file out of this entire tutorial?
So that people working in offline mode also can have the joy of working with this fantastic tutorial.
Please reply to: salve0@hotmail.com
Thanks!
Alex…u r the administrator and can delete that spam msgs right? pls do it fast..bcoz thts really disturbs..thts not suitable in this place..we people need serious discussion abt programming in C++..pls do care abt these types of spams..
thanks.
Thank u very much for this course ;)
Very nice lesson Alex, I have learned a lot so far and hope to get some great knowledge from this, as far as the 2 idiots commenting earlier, they sound like typical day labor losers. They couldn’t figure out how many beers would be left in a 12 pack if you took 3 out.
When i code i place the:
at the top
#include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; }it still works, isn’t that more convinient? or is there a reason for placing it inside each and every function
Hello! I, Amar from bokaro, Student of Doeacc A level. O level of the mark behind. Just send me extremely important solved problem in my E-mail add. that’s why as i am beginner in c++. And i hope that i must became the most powerful in c++, because i believe only in work. have a good day.
you gys need to stop smoking bad weed, the code is fine.