C++ Workshop - Getting Started with C++ (Ch. 1 & 2)

Started by
182 comments, last by Dbproguy 15 years, 11 months ago

Welcome to the GDNet C++ Workshop – Ch. 1 & 2

For a complete introduction to this workshop, please look here. Workshop Overview This workshop is designed to aid people in their journey to learn beginning C++. This workshop is targeted at highly motivated individuals who are interested in learning C++ or who have attempted to learn C++ in the past, but found that without sufficient support and mentoring they were unable to connect all the pieces of this highly complex but powerful programming language. This is a 'guided' self-teaching C++ workshop. Each student is responsible for taking the time to read the material and learn the information. The community and tutors that arise out of this workshop are here for making the learning process run more smoothly, but are not obligated to baby-sit a person's progress. Because everyone will be working from the same textbook (Teach Yourself C++ in 21 days 5th Ed.), students may find it easier to get answers to the specific questions they might have. There is no minimum age requirement, and there is no previous programming experience required. Additionally, this workshop does not attempt to defend C++ as a language, nor does it attempt to demonstrate that C++ is either more or less useful then other programming languages for any particular purpose. People who intend to start a discussion about the differences between C++ and ANY other languages (except as are relevant to a particular discussion), are encouraged to do so elsewhere. This workshop is for educational, not philosophical discussions. Quizzes & Exercises Each chapter will have quizzes and exercises. Please try and answer them by yourself. If you try with reasonable effort but are unable to answer the questions or complete the exercises, feel free to post a clarification question here on the thread. Tutors, myself, or others will do the best we can to point you in the right direction for finding the answer.

Chapter 1 – Getting Started, Chapter 2 – The Anatomy of a C++ Program

Introduction Greetings! Most weeks will be 7 days, beginning on Monday and ending on Sunday, however as this week starts on Thursday, and is the first “week” in the class, we will extend it to a full 10 days to get on a better schedule and give people a chance to obtain their textbooks in the mail. Additionally, as the topics are relatively straight forward, requiring little programming, etc…Week 1 will be a combination of the first 2 chapters. Chapter 1 is about 16 pages and chapter 2 is an additional 14 pages. Participants have 10 days ( ending Sunday, June 10th ) to read the first two chapters, at which point we will move on to the next chapter. Participants are welcome to post their questions for these chapters within this thread and myself, the tutors, and other participants will do the best we can to answer your questions. As the thread is likely to grow to a hundred or more posts, the C++ workshop threads will be closely moderated. Discussions which become narratives, flame-wars, or philosophical will either be removed or moved to another forum, unless entirely relevant to the current chapters. If you have trouble installing your compiler or getting “Hello World” to build, please ask for help. You will not be able to move forward with the workshop until you’ve done those two tasks successfully. Good Luck! Finally, feel free to post quiz-like questions after about 5 days. This will give people an opportunity to test their knowledge and understanding after they’ve had a chance to absorb the information. For questions which require further research then what is in the book, mark the question with an [Extra Credit] tag. Topical Outline of the Reading (Not literal due to copyrights)
  1. A History of C++
  2. Which language should be learned first C or C++?
  3. How does C++ compare to Java and C#?
  4. An introduction to Managed C++
  5. The ANSI Standard
  6. Getting in the right mindset to program
  7. How an .exe gets created
  8. Building your first program. – “Hello World”
  9. An introduction to compiler errors
  10. A review of Hello World
  11. An introduction to “Console Out”
  12. An introduction to the Standard Namespace
  13. Commenting your code
  14. An introduction to functions
  15. The difference between Methods and Functions
Additional Resources None...

Creating and Building a Project w/ VC++ .NET 2005

It has come to my attention that the instructions for creating a project/file in the book on pages 19-20 are for Visual C++ 6. Visual C++ .NET 2005 is actually version 8. The correct approach for .NET 2005 is: Step 1: Create an empty project
  1. File->New->Project
  2. Select 'Win32' from Project types
  3. Select 'Win32 Console Application' from the Templates
  4. Type the name of the project and the location in the edit box near the bottom.
  5. Click OK
  6. When the dialog box appears click on "Application Settings" on the left
  7. Click "Empty Project" under Additional options.
  8. Click Finish
Step 2: Add files to your project
  1. Right click on your project in the Solution Explorer
  2. Add->New Item
  3. Click Code in the Categories List
  4. Select either C++ File or Header File as appropriate to the task
  5. Type the name of the file in the edit box near the bottom.
  6. Click Add
Building your executable For solutions which only have a single project, Build Solution will do the same as "Build <projName>". Once you have solutions which are containers for multiple projects, you will need to choose either to build individual projects, or the whole solution. I believe all of the tasks we will attempt in this workshop will require only a single project. As such, "Build Solution" should work just fine. Week 1 Errata Chapter 1, Exercise 1 says "...try to guess what it does without running it." If you DO put it into a compiler it will give you a compile error as the listing is not correct. The author meant:

#include <iostream>
int main()
{
    int x = 5;
    int y = 7;
    std::cout << std::endl;
    std::cout << x + y << " " << x * y;
    std::cout << std::endl;
    return 0;
}
Note that 'endl' is also part of the Standard Namespace, and thus requires std:: at the beginning. [Edited by - jwalsh on May 30, 2007 5:25:07 PM]
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
Advertisement
There are many IDEs available for use with C++. The textbook describes getting started with Visual C++ 6.0. The process is fairly similar under newer versions of Visual C++. There are also several other, widely used and free, IDEs for windows. What follows are the instructions provided by the textbook converted to the two most popular of these, Dev-C++ and Code::Blocks. Which one you choose is up to you. They are different IDEs but the code presented in the text will work the same on any of these compilers. The recommended IDE for the workshop is still Visual C++ EE

Getting Started With Your Compiler
-- Dev-C++ Version --


You can download Dev-C++ for free from here. The following instructions assume that you have download and installed Dev-C++ correctly. installing it is easy, just run the installer, and when in doubt select everything. [smile]

Building the Hello world Project

To create and test the Hello World program, follow these steps.

1. Start Dev-C++.
2. Choose File, New, Project from the meus.
3. Choose Empty Project and enter a project name, such as hello. Make sure "C++ project" is selected, and not "C project". Click Ok.
4. Save the .dev file. Preferably this should be in a new folder created to store all the files for this project - "\Projects\hello\hello.dev" for example.
5. Choose File, New, Source File from the menus. Click yes when it asks you if you wish to add the source file to the project.
6. Choose File, Save from the menus. Call the new file "main.cpp". This should be in the same directory as your .dev file, so as per the previous example "\Projects\hello\main.cpp".
7. Enter the code as indicated previously.
8. Choose Execute, Compile from the menus.
9. Check that you have no build errors. You can find this information near the bottom of the editor.
10. Run the program by selecting Execute, Run from the menus.

NOTE:
When you run the program, it will more than likely flash on screen and disappear again. The reason for this is that the program is finished and exits straight away. The solution is described in the FAQ just under this section in the textbook (Page 20).

Getting Started With Your Compiler
-- Code::Blocks Version --


You can download Code::Blocks from here. Download "Code::Blocks IDE, with MINGW compiler" if on Windows. The following instructions assume that you have downloaded and installed Code::Blocks correctly.

Building the Hello world Project

1. Start Code::Blocks.
2. Choose File, New Project... from the menus.
3. Select Console Application. Ensure that "C++ source" is selected in the File(s) options box. Select "Do not create any files". Click Create.
4. Save the .cbp file. Give it the name of your project. In this case "hello.cbp". Preferably this should be in a new folder created to store all the files for this project - "\Projects\hello\hello.cbp" for example.
5. Choose File, New File from the menus.
6. Call the file "main.cpp" and click Save. This should be in the same directory as your .cbp file, so as per the previous example "\Projects\hello\main.cpp". Click yes, when it asks you if you want to add the new file to the active project.
7. Enter the code as indicated previously.
8. Choose Build, Build from the menus.
9. Check that you have no build errors. You can find this information near the bottom of the editor.
10. Run the program by selecting Build, Run from the menus.
11. Press enter to end the program.
Hello all,

My apologies if these questions are a bit too ridiculous...I've been out of programming for five years (since college) and decided to take a shot at it again here.

1. With the suggested IDE, the line ' #include "stdafx.h" ' seems to be a mandatory line of code that must be included on line 1. Is this required only for this IDE? And if so, why?

2. After getting Hello World! to run, I attempted to compile and run the additional exercise programs and received the following errors with the "12 35" pgm:

error C2065: 'end1' : undeclared identifier
error C2065: 'end' : undeclared identifier

I'm kind of clueless on this one - do I need to declare these somewhere in the pgm?

I'd like to also thank Mr. Walsh and the tutors for putting this together, I may be a noob but I plan on staying true to the workshop:)
Don't know about what stdafx.h is used for, but your 'undeclared identifier'-problem is that it's supposed to be 'endl', ie. it should end with a lowercase L, not 1. So just change end1 and end to endl and it should work.
[opinion]
In chapter 1, the book mentions that some IDEs may flash the console window up then disapear too quickly to read. The book recommends waiting for the user to input a character and press enter. This may work well in the IDE, but when you run the program through the actual command prompt, it will seem silly to do this. If you are using a version of Visual Studio, a better way would be to "Start without debugging". This will ensure that the console window remains up after the program finishes.
[/opinion]

Good luck to everyone with the first week! These two chapters are going to introduce you to the basics of forming any C++ program. They are important regardless of whether you have programmed in another language or not. If you are still waiting on the book, check out the online version (google "Teach yourself C++ in 21 days" -> first link. Can't get the link to work because of the plus signs) to make sure you don't get behind.



Quote:Original post by Palejo
Hello all,

My apologies if these questions are a bit too ridiculous...I've been out of programming for five years (since college) and decided to take a shot at it again here.

1. With the suggested IDE, the line ' #include "stdafx.h" ' seems to be a mandatory line of code that must be included on line 1. Is this required only for this IDE? And if so, why?

2. After getting Hello World! to run, I attempted to compile and run the additional exercise programs and received the following errors with the "12 35" pgm:

error C2065: 'end1' : undeclared identifier
error C2065: 'end' : undeclared identifier

I'm kind of clueless on this one - do I need to declare these somewhere in the pgm?

I'd like to also thank Mr. Walsh and the tutors for putting this together, I may be a noob but I plan on staying true to the workshop:)


1. When creating a console project, make sure to check "Empty project" in the app wizard, then add a single source file for the code. This is known as a precompiled header and is really not necessary for this program. I personally never use them, but they can help speed up compiling very large projects.

Edit: Read Fruny's response for a much better explaination.

2. it is "endl" (with an "L" not a "one"). Unfortunately, most fonts have these look very similar, so be very careful when copying them out of a book. "endl" is short for "End line" and indicates you want to start a newline.
Sean Henley [C++ Tutor]Rensselaer Polytechnic Institute
Quote:Original post by Palejo
1. With the suggested IDE, the line ' #include "stdafx.h" ' seems to be a mandatory line of code that must be included on line 1. Is this required only for this IDE? And if so, why?


When you #include a header file (or any kind a file, for that matter), its contents are literally added to the file you are compiling. The content of those header files quickly add up to large amounts of code which generally doesn't change much - since you generally don't go around modifying the contents of <iostream> or <windows.h> - but still need to be compiled each and every time.

So, as a speed-up, Visual Studio offers the concept of precompiled headers. When a header is designated as a precompiled header, the compiler will process it and then save its state. That way, the next time the precompiled header is included, that state can just be restored, rather than re-compiling it all.

By default, Visual Studio is set up to use "stdafx.h" as its precompiled header (along with the associated source file, which shouldn't be modified by you). If you create a new project and look at that header, you'll notice that there already is a bit of code in there.

Now, if you don't include it but still leave VS set up to expect it, or if you #include other things before the precompiled header, you will get errors. You can change the name of the file to use as precompiled header (though there is little reason to), or completely disable them (if you just have a small program you are writing to test things) by right-clicking on your project name in the Solution Explorer (the tab where all the files in your project are listed), and selecting Properties, going to Configuration Properties, C/C++, Precompiled headers.

Quote:2. After getting Hello World! to run, I attempted to compile and run the additional exercise programs and received the following errors with the "12 35" pgm:

error C2065: 'end1' : undeclared identifier
error C2065: 'end' : undeclared identifier

I'm kind of clueless on this one - do I need to declare these somewhere in the pgm?


It is a typo, you want endl with a lowercase L at the end.

Quote:I'd like to also thank Mr. Walsh and the tutors for putting this together, I may be a noob but I plan on staying true to the workshop:)


You are most welcome.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Quote:Original post by Palejo
1. With the suggested IDE, the line ' #include "stdafx.h" ' seems to be a mandatory line of code that must be included on line 1. Is this required only for this IDE? And if so, why?

You probably created a project with standard files. But it's actually recommended that you start a [console] project that is empty. Then add a new source file, usually 'main.cpp'.

Quote:Original post by Palejo
2. After getting Hello World! to run, I attempted to compile and run the additional exercise programs and received the following errors with the "12 35" pgm:

error C2065: 'end1' : undeclared identifier
error C2065: 'end' : undeclared identifier

This is probably a typo. Try using 'endl'. (If you didn't notice, it ends with an L)

Quote:Original post by Sr_Guapo
[opinion]
In chapter 1, the book mentions that some IDEs may flash the console window up then disapear too quickly to read. The book recommends waiting for the user to input a character and press enter. This may work well in the IDE, but when you run the program through the actual command prompt, it will seem silly to do this. If you are using a version of Visual Studio, a better way would be to "Start without debugging". This will ensure that the console window remains up after the program finishes.
[/opinion]


[opinion]

It is actually a pet peeve of mine: console applications should rarely be modified to "stay up" after they have completed what they are doing. Imagine you are copying files in Explorer. You select them and control-drag them somewhere else. You wouldn't want to have a message box pop up telling you "oh, by the way, I'm done" every time you copy some files.

Having a console application wait for a key once it has finished its task is just as rude.

The reason why the console window closes after the program is complete is simply because you started the application from within a GUI environment. The application needs a console window, so the GUI creates one. Once the application has exited, the GUI destroys the window. Simple. The console application itself is not aware of the conditions it is running in.

The natural environment for a console application to run from is, unsurprisingly, form a pre-existing console. Open such a console by hitting Start -> Run and typing cmd.exe. ( Or, more interestingly, in your Start Menu, go to Microsoft Visual Studio -> Visual Studio Tools -> Visual Studio 2005 Command Prompt. This will give you direct access to the VS C++ compiler from the command line. )

Now you can start typing commands, moving from a folder to another with CD, displaying its contents with DIR or running any other program by just typing its name. Now imagine that every time you change directories, or do anything else, you'd get asked "Press a key to continue".

That would get old very quickly, trust me.

Even worse, applications are often combined together using scripts (called Batch Files under DOS and Windows). You could, for example, write an application that downloads images (or other files) then resizes them. If you were to hardcode a wait for user intervention into your program, there would be no way the script could run unattended, and you would have to sit there, pressing a key to continue every time you get asked to do it.


Asking for the user to press a key when the program has completed is not good practice. Don't do it. Visual Studio will automatically pause for you when you Run Without Debugging, as Sr_Guapo pointed out. If you open a console (cmd.exe), cd to where your program is stored and run it from there, the console window will not close (AND you can reuse it to run your program again and again) or, you can write a script that runs your program and then executes PAUSE.

But please, please, please, I beseech you. Do not embed that pause into your program.

[/opinion]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Wow. Thank you for the fast responses and information:)

My pgm, however:

// Exercise1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

int main()
{
int x = 5;
int y = 7;
std::cout << endl;
std::cout << x + y << " " << x * y;
std::cout << end;
return 0;
}

Still gets me:

error C2065: 'endl' : undeclared identifier
error C2065: 'end' : undeclared identifier

I've been staring at the code for a while now, making sure there are no typos...
[opinion]
I tend to agree with Fruny on this one. It is almost never a good idea to add code which changes the behavior of your application for any other purpose then changing its behavior for its own sake.

The most common reasons people modify their source for "external" reasons is to keep a console window open or to print debug messages to the console. Although these seem harmless, Fruny has already described reasons you wouldn’t want to force keyboard input, and as far as debug messages - you must be VERY careful when doing this that you don’t modify the behavior of the code in any way. Otherwise, removing those lines at a later date, commenting them out, or #ifdef'ing them can actually change the behavior of your program, making it unpredictable...cont.
[/opinion]

The main point is: The more lines of code you have, the more lines of code which can presumably cause compile or logic errors.

[opinion]
...For me (using Visual C++), I use F5 to run my program in debug mode only when I've got a breakpoint set and something I want to step through. The rest of the time I use CTRL+F5 which launches the program NOT in debug mode. As was pointed out, this prevents the console dialog from closing after termination of the program.
[/opinion]

An alternate to using debug messages is to become intimately familiar with the debugging capabilities of your compiler. I encourage all new programmers to, as an exercise, intentionally make errors in their code, set breakpoints, and run their code so they can step through and see the variables, memory, and even registers changing as they step. Becoming proficient with your debugger will make you infinitely more productive. All programmers make mistakes ('cept for me), so its best to learn how to find your mistakes efficiently.

For the record, stepping through your code, checking values, etc...is sometimes referred to as "White-Box" testing, because you're able to evaluate the internals. Just checking input/output values, and throwing in occasional output messages is sometimes referred to as "Black-Box" testing...because the actual behavior is hidden from you, as if in a Black box.

[opinion]
Whenever possible/practical, use White-Box testing at this state of learning.
[/opinion]

Cheers!
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints

This topic is closed to new replies.

Advertisement