Title: Newbie-FAQ
Description: Read before you ask
dr voodoo - December 4, 2005 05:33 PM (GMT)
Editor: KTC and DrVoodoo
Credit: EVERYONE at C++ Learning Community who have ever provided any answer to any of the above questions, Marshall Cline's C++ FAQ Lite, The alt.comp.lang.learn.c-c++ FAQ, Comeau Computing, Jack Klein, Bjarne Stroustrup, ISO/IEC 14882.
dr voodoo - December 4, 2005 05:34 PM (GMT)
Visual C++ the same as C++ right ?
No, C++ is a programming language, whereas Viusal C++ is a commercial IDE and compiler package by Microsoft.
dr voodoo - December 4, 2005 05:35 PM (GMT)
Okay, do people actually uses C++ ?
What programs are written in C++ ?One word: YES!
Take a look at
http://www.research.att.com/~bs/applications.html for a quick list of things built with C++.
dr voodoo - December 4, 2005 05:37 PM (GMT)
Should I learn C before I learn C++ ?
If you want to know C, learn C, otherwise, if your ultimate goal is to know C++, then don't bother.
| QUOTE (C++ FAQ Lite @ Marshall Cline) |
If your ultimate goal is to learn OO/C++ and you don't already know C, reading books or taking courses in C will not only waste your time, but it will teach you a bunch of things that you'll explicitly have to un-learn when you finally get back on track and learn OO/C++ (e.g., malloc(), printf(), unnecessary use of switch statements, error-code exception handling, unnecessary use of #define macros, etc.).
If you want to learn OO/C++, learn OO/C++. Taking time out to learn C will waste your time and confuse you. |
| QUOTE (Stroustrup FAQ) |
The common subset of C and C++ is easier to learn than C. There will be less type errors to catch manually (the C++ type system is stricter and more expressive), fewer tricks to learn (C++ allows you to express more things without circumlocution), and better libraries available. The best initial subset of C++ to learn is not "all of C". |
dr voodoo - December 4, 2005 05:42 PM (GMT)
Where can I get a free compiler then ?Please consider also reading :
I want to start with C++. What programs do I need?If you're using Linux and the like, then the obvious choice would be the GNU C++ compiler. It comes with most Linux distro already, otherwise download it from
GNU Compiler CollectionOn Windows, there's various compiler one can try:
- MinGW - A port of the GNU C++ compiler to Windows. Is very standard conform in comparison to other compiles. It produces moderately optimized code.
- Borland Command Line Compiler - Borland has made it's compiler version 5.5 freely available for download. This is not the newest version and it does contain bugs, notably with exceptions, and doesn't stick strict to the standard when it comes to templates. Also the produced code can only hardly compete with more modern compilers. However if you only want a working compiler for older source codes then this might be what you are looking for.
- MS Visual C++ Toolkit 2003 - This is the same compiler as Microsoft ships with the commercial version of VC. It is good at compiling standard compliant code although it does contain a great number of extensions. It is also good at optimizing code. Win9x (Win95/Win98/WinME) is not supported. The platform SDK is also needed if you want to build WinAPI programs.
- Digital Mars C++ - Another command line only compiler, fast compile time.
- Open Watcom C++ - Open source follow-up to Sybase Watcom C++ compiler. Not the most up-to-date in regards to implementation of the standard but are getting there.
For MS-DOS (Anyone still actually uses DOS?? blink.gif ):
- DJGPP - MS-DOS port of GCC. Can also be used to build Win32 console applications.
For Mac
For other platforms you might find something
here.
dr voodoo - December 4, 2005 05:44 PM (GMT)
Which online tutorial should I use ?What books should I get ?A word of warning before we start, most tutorials on the internet is either badly out-of-date, crap, or just plain incorrect.
Therefore, one should obtain (buy, beg, or borrow :D) some good books to supplement the learning if one does decide to use online tutorials.
A good introduction to the WinAPI can be found at
One should get more than one book to learn C++ from as no one book can teach you everything you need to know:
As always, the above list can't cover every book that deserve to be there, so take a look at
http://www.accu.org/bookreviews/public/index.htm for some book review from expert in C++. (Do take note of the review date as old review means the book might no longer be up to date)
dr voodoo - December 4, 2005 05:45 PM (GMT)
My program flashes and then vanishes!! ?How do I get the command prompt to stay open after program finishes ?First, an explanation of why it flashes and then closes is necessary here.
Under Windows, and possibly other OS as well, one can run a console program by double clicking on it. This will cause the OS to open a console window. Then the OS transfers the control and window to the program, meaning runs it. After the program is finished its job it transfers the window and the control back to the OS. The OS regards the job as finished and therefore closes the window.
There's several different way one can make the command prompt stay open after a program finishs running. So that one can actually read the output.
- Run the program from the command promt. In this case te OS doesn't open a new window for your program but transfers the window of the command promt to the program. After it is finished the window is transfered to the command promt and not the OS so the window stays open.
- An alternative is to keep the program from finishing before the user has read the output. Meaning ask the user if he has read the output in some way. There are several ways to do this.
[LIST] - Add the line system("PAUSE"); to the end of the program just before the return statement. The function std::system( const char* ) is declare in <cstdlib>, it takes a C-style character string and executes it as if it was entered into the command promt*. PAUSE is a windows program that writes a note to the console that the user should press a key to continue and then waits until the user presses a key. (Side effect: The string "Press any key to continue..." is localized, meaning for example on a French Windows version the string would be "Appuyez sur une touche pour continuer...")
- Read some dummy variable. This only works if there's nothing in the input buffer because otherwise the buffer content is read before the user is asked for input.
- Tell cin to ignore all input until Enter is pressed. (Again, only works if there's nothing already in the input buffer.) This can be done with
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); - Hope that the input buffer is empty and simply read a character. This works especially well for output only programs. This can be done with cin.get()
[/list]
* Actually a new environment is created to execute only that string. This means that for example system("SET A=5") to set an environment variable will not work.
dr voodoo - December 4, 2005 05:46 PM (GMT)
Can I write void main() ?
main() returns void, right ?
Can I just write main() ?
No, no and NO!
For a standard conforming program, main() always, ALWAYS return int. void main() is not and never has been C++ (or even C for that matter). According to the ISO/IEC C++ standard 3.6.1[2], the two acceptable definition of main is
| CODE |
| int main() { /* ... */ } |
and
| CODE |
| int main( int argc, char* argv[] ) { /* ... */ } |
Note also that ISO C++ (or C99) does NOT allow you to leave the return type out of a function declaration so that the return type is implicitly assumed to be int.
Note the above applies only to hosted environment, none of it applies to freestanding environment, which does not require to have main(). However, chances are, if you're reading this, you'll be in a hosted environment.
Here some links to other sites speaking about void main and co.
- http://home.att.net/~jackklein/ctips01.html#int_main
- http://www.comeaucomputing.com/techtalk/#voidmain
- http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.3
- http://ma.rtij.nl/acllc-c++.FAQ.html#q3.4
- http://www.eskimo.com/~scs/C-faq/q11.12.html
dr voodoo - December 4, 2005 05:47 PM (GMT)
What shall main() return then ?
The three values which one can use for program termination according to ISO C++ are 0, EXIT_SUCCESS, or EXIT_FAILURE (These two macros are defined in <cstdlib>). 0 and EXIT_SUCCESS represent a successful program termination, whereas EXIT_FAILURE represent unsuccessful. Any other return value produce a program termination status that is implementationally-defined.
dr voodoo - December 4, 2005 05:47 PM (GMT)
What's the difference between <iostream> and <iostream.h> ?Why doesn't cout, or anything from the Standard Library work ?What's this namespace thing about ?What is this std:: that appears in front of cout in other people's codes?<iostream> is the correct header name. Unlike in C, ISO C++ standard headers does not have
.h suffix.
When C++ was first invented, the io function was provided in a header file call
iostream.h . A few years later, while the C++ standard was being worked on, namespaces was invented and put into C++. Since then, the correct header name for the io function is
iostream (without the .h). At the same time, all the function that are provided for you in any of the standard header files are declared to be inside std namespace. Namespace essentially allows variables and fuction to be localized to certain area of codes. So, for example, two programmers working on the same program wouldn't have to worry about some of their variables having the same name.
There's three way for you to access the various functions provided by the standard headers:
- You can fully qualify what namespace the function or object you're trying to access is in
| CODE |
| std::cout << "hello, world\n"; |
- You can use a "using declaration"
| CODE |
using std::cout; .... cout << "hello, world\n"; |
- Lastly, you can use a "using directive"
| CODE |
using namespace std; .... cout << "hello, world\n"; |
The using directive dump everything into global scope, allowing you to use all of the C++ standard header functions without qualification. This is not recommended as it defeats the purposes of having namespace in C++, but for just starting out, you might find this the most convenient.
dr voodoo - December 4, 2005 05:48 PM (GMT)
What's the difference between std::endl and '\n' ?
'\n' send to output buffer a newline, std::endl sends the newline and then flushes the output buffer (i.e. actually print the thing out on the command prompt). As such, std::endl is more expensive performance wise. So use only when you actually need to flush the output buffer.
dr voodoo - December 4, 2005 05:49 PM (GMT)
How do I generate a (pseudo)random number ?
Why isn't my random numbers random at all ?
How do I use rand() so it doesn't produce the same numbers each time my program is run ?
"The function rand() as provided in <cstdlib> computes and return a pseudo-random integers between 0 and RAND_MAX where RAND_MAX is at least 32767.
The function srand( unsigned int ) uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand() .
Note that if rand() is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1."
| CODE |
// Examples of generating random numbers using rand() and srand() #include <cstdlib> #include <ctime> /* .... */ srand( time( NULL ) ); // Seeds rand(). Remember to only call ONCE in your program!
int random1 = rand(); // random number between 0 and RAND_MAX int random2 = rand() % (n + 1); // random number between 0 and n (including n) int random3 = (rand() % n) + 1; // random number between 1 and n (including b) int random4 = (rand() % (y - x)) + x; // random number between x and y (including x, excluding y)
|
dr voodoo - December 4, 2005 05:50 PM (GMT)
Why shouldn't I use == to compare two floating point number ?
Okay, this is a computer science issue rather than C++, but here goes anyway...
The problem is floating point number can only represent a finite set of numbers. In an ideal world, all the rational & irrational numbers can be stored. However, since that's not the case, some (most!) floating point numbers cannot be represented exactly. Now since == only return true if the two item being compared is EXACTLY the same, comparisons with floating points number don't always do what you expect.
So to compare two floating point numbers, one need to check whether they are very close to each other. One such method (among many) is
| CODE |
if( std::abs( a - b ) < precision ) // a == b |
Couple of place you can read more about floating point and its computation:
What Every Computer Scientist Should Know About Floating-Point Arithmetic - Classic text, need to know your mathematics! Loads of images, so can take a while to load.
Doug Priest supplement to above paper
dr voodoo - December 4, 2005 05:51 PM (GMT)
Any website with reference to the standard library ?Is there a list of every "command"?The standard library is a collection of a number of useful functions. It should ship with every compiler.
- C/C++ Reference - Good but incomplete. I would recommend this reference for beginners.
- Dinkum C++ Library Reference - Seems to be complete.
- C++ Library Reference - Another good site. Non-iostream C++ library still under construction.
- SGI STL Programmer's Guide - Very good site with easy to use STL lookup. Doesn't contain iostream.
- MSDN - Microsoft's site about the Windows API. It also contains a documentation of the C runtime library shipped with VC and which contains most of the standard C functions. Note that the WinAPI is not part of the C++ standad library.
dr voodoo - December 4, 2005 05:52 PM (GMT)
Where can I get a copy of the ISO/IEC C++ Standard ?A copy of the standard can be obtained from ISO and various national standard organizations at a fee.
Now since I assume you wouldn't want to pay 10 times more than you have to, I'll suggest you get it off one of the national organization ;) A list of members of ISO and contact details:
ISO Member bodiesCouple of quick links:
INCITS/ISO/IEC 14882:2003 - $18.00 USD available for immediate download on payment.
The C++ Standard : Incorporating Technical Corrigendum No. 1 - Hardcopy by British Standards Institute $65.00
Now I hear you ask whether there's anything available for free on the internet. If you're willing to put up with something that's non-authorative, out-of-date, and in some places, slightly incorrect, then the answer is yes :)
Committee Draft #2 (CD2) of the 1998 C++ standard -
hereList of corridenda (corrections/updates/clarifications) voted into the 2003 standard -
hereHome of the C++ standard committee. Contain C++ Standard Core Language, Standard Library Active Issues, Closed Issues & Defect Report List.
dr voodoo - December 4, 2005 05:53 PM (GMT)
How do i make a full screen console window?well an easy way is by simulating the keyboard shortcut keys
click here for how to make a fullscreen console window under the windows operating system
dr voodoo - December 4, 2005 05:54 PM (GMT)
Im using Dev-c++ and i cant seem to make an exe...
if that is your problem there is a good chance that you downloaded the version of dev c++ that only contains a code editor and not the editor and the compiler. to be sure you get a compiler with dev c++ the download should be around 12mb. (as of 7/12/2004 anyway)
dr voodoo - December 4, 2005 06:06 PM (GMT)
I found an error in the FAQ, have an addition to make or want to discuss about the FAQ. What should I do?If you have found an error in an answer or have an addition to make to an existing answer simply post in this thread. I will from time to time update the answers and then remove your post. Note that I also want to keep the answer simple so if your addition goes to in depth then I might not add it to keep the FAQ understandable for newbies.
If you want to add a new question and answer simply post it in this thread. Use bold and size 7 for the question. I will add it to the index when I do an update.
If you want to have a general discussion about the FAQ then post in the community
forum.
dr voodoo - December 4, 2005 09:05 PM (GMT)
I want to start with C++. What programs do I need?C++ is a language and not a specific program and therefore there a large number of programs exist capable of creating C++ applications called "compiler". Additionally to make these programs useful you need some sort of code editor called "IDE". There are commercial and free compilers and IDEs. For beginners a free all-in-one-installer is probably the best choice. Here is a list of some of the available packages for Windows:
- MinGW Developper studio / direct download link - My personal favourite. Pretty much bug free and has only the really needed functionality and therefore doesn't overwhelm beginners with options.
- Dev C++ / download link - Probably the most famous IDE for beginners. However I personally do not understand why as it contains quiet some bugs and fighting with messed up makefiles is in my eyes not trivial.
- Code::Blocks / download link - A rather new IDE which is in my eyes a bit too complicated for the average beginner to programming. People who however are switching from some other languages to C++ should be able to handle it. It is really good for hobby developers.
Also note that in C++ you start with console applications and only very slowly you move on to graphical applications or window applications.
After having set up your compiler and IDE you will probably want a tutorial to get you started. There is also a
FAQ entry for this.
dr voodoo - January 21, 2006 08:16 PM (GMT)
How to post topics the right way.It is hard to define what a good topic is as this heavily depends on the subject. However here I will give a few general hints for 3 common groups of subjects: "Why doesn't xy run/work?", "Why doesn't xy compile?" and "How does feature xy work?”
Why doesn't xy run/work?
- Post a minimal (max:100 lines) but compilable example illustrating your problem.
- Post what you want the code to do.
- If the program takes any sort of input, for example reads from cin or has a GUI, then provide the input needed to make the problem show.
- If the program produces wrong output then provide the output that you would expect and the output produced by the program.
- If the program crashes then provide details about how it crashes. Tell if the program just quits or if some sort of error message is produced.
- If you think that you know which part of your minimal example could be then tell it.
- Information about the compiler, libraries and OS is never wrong.
- Try to use a descriptive and non aggressive title. "strcpy crashes" is better than "!!!!!!!!!!!!! HELP !!!!!!!11111 URGENT". (Yes, there are people that use titles such as the second).
- Do not use all uppercase. If you want to mark some word specially then use bold which is much simpler to read than UPPERCASE.
- :codeblks:
Why doesn't xy compile?
- Post a minimal (max:100 lines) example illustrating your problem.
- Post the first 10 error message produced by the compiler when compiling that minimal example.
- Post what you want the code to do.
- It is never wrong to tell which error refers to which line as the board doesn't indicate line numbers with the code.
- Information about the compiler and libraries is never wrong.
- Try to use a descriptive and non aggressive title. "const problem" is better than "!!!!!!!!!!!!! HELP !!!!!!!11111 URGENT". (Yes, there are people that use titles such as the second).
- Do not use all uppercase. If you want to mark some word specially then use bold which is much simpler to read than UPPERCASE.
- :codeblks:
How does feature xy work?
- Google for an answer. It is very likely that you will find an answer. However if you have no luck you are always welcome to ask here. (People know about which subjects you are sure to find something so it would be better to do it.)
- Reread your post and ask yourself: Can anybody understand what I am writing?
- Try to use a descriptive and non aggressive title. "const problem" is better than "!!!!!!!!!!!!! HELP !!!!!!!11111 URGENT". (Yes, there are people that use titles such as the second).
- Do not use all uppercase. If you want to mark some word specially then use bold which is much simpler to read than UPPERCASE.
- :codeblks: