Common Errors in C++ Syntax
First off - About Section 2:
This section is going to be very short. On this page, we are only going to name some common mistakes and pointers or what to watch out for while beginning your journey into the realm of C++. Next we'll take a quick look at some of the common types of data in C++. We'll also discuss some of the legal variable naming conventions, and which ones are considered in "good taste". And finally, a couple of short programs to show some of the differences in data types and things to think about when working with them.
Now back to your regularly scheduled tutorial:
Some of the most common errors in C++ are typos. Check your program carefully to prevent these. Here are some of the more common errors:
- Mispelling names of variables. Remember case counts! The variables "newheight" and "newHeight" are not the same. Be careful to not define a variable "ttlRadius", and later call it as "totalRadius". These will generate "unknown variable" errors when compiling.
- Forgetting to use a semi-colon (;) at the end of each statement. These are usually easy to spot, generating "expected ;" errors on compilation.
- Wrong use of insertion / extraction operators, such as "cout >>" or conversly, "cin <<". Notice these are supposed to be "cout <<" and "cin >>".
- Defining a datatype, and assigning to it a different datatype. Many times this will only give a logical error, meaning the program will still compile and run, but give erroneous output or crash. An example of this would be to assign a float type to a int variable. It can be done, and the compiler will "cast" it without complaint, but further operations on the float-turned-integer may turn out erroneous data.
- Forgetting to "return 0;" at the end of the program.
- Missing / extra opening or closing curly-braces ( { , } ). These can be difficult to track down sometimes, and therefore good formating style must be used to help locate them easily.
- Using an assignment operator (=) in lieu of a relational operator (==) or vice versa. An assignment operator (=) is normally used for "assigning" a value to a variable (PI = 3.14); whereas a relational operator for is-equal-to (==) is used to determine if two values are equal or not and returns a true or false value (PI == 3.33 would return false or 0).
These are just a few of the most common errors. C++ can be difficult to the beginner, and even to more advanced people. We've seen, many times, posts to newsgroups or mailing lists with questions like "why won't this code compile" and then the answer comes from either the original poster or someone else, with what turns out to be a mispelling or a bad definition (ie, "#include <iostreem>" - okay, maybe not quite that simple, but you get the picture). Sometimes it takes an outside person to spot one of those simple errors that you've overlooked many times, but at least try to look first before posting.
Now that we've gotten that bit out of the way, on to data types.