Common Beginner C++ Programming Mistakes

Similar documents
6. Control Structures

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Chapter 8 Selection 8-1

Passing 1D arrays to functions.

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Appendix K Introduction to Microsoft Visual C++ 6.0

13 Classes & Objects with Constructors/Destructors

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Basics of I/O Streams and File I/O

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Lecture 2 Notes: Flow of Control

Moving from C++ to VBA

if and if-else: Part 1

While Loop. 6. Iteration

Chapter One Introduction to Programming

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Answers to Review Questions Chapter 7

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Informatica e Sistemi in Tempo Reale

C Programming Structure of a C18 Program

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Independent samples t-test. Dr. Tom Pierce Radford University

C++FA 5.1 PRACTICE MID-TERM EXAM

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

C++ Input/Output: Streams

Computer Programming C++ Classes and Objects 15 th Lecture

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Lab Experience 17. Programming Language Translation

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Conditions & Boolean Expressions

J a v a Quiz (Unit 3, Test 0 Practice)

The first program: Little Crab

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

UEE1302 (1102) F10 Introduction to Computers and Programming

Boolean Logic in MATLAB

Sequential Program Execution

Comp151. Definitions & Declarations

2 The first program: Little Crab

Java Interview Questions and Answers

Lecture 22: C Programming 4 Embedded Systems

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Compiler Construction

Learning Computer Programming using e-learning as a tool. A Thesis. Submitted to the Department of Computer Science and Engineering.

Statements and Control Flow

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

7.7 Case Study: Calculating Depreciation

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Member Functions of the istream Class

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

1. The First Visual C++ Program

C++ INTERVIEW QUESTIONS

COMPUTER SCIENCE 1999 (Delhi Board)

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Chapter 5. Selection 5-1

**Unedited Draft** Arithmetic Revisited Lesson 4: Part 3: Multiplying Mixed Numbers

Using C++ File Streams

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

The While Loop. Objectives. Textbook. WHILE Loops

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

Ch 7-1. Object-Oriented Programming and Classes

Beginner s Matlab Tutorial

F ahrenheit = 9 Celsius + 32

Object Oriented Software Design

arrays C Programming Language - Arrays

Visual Studio 2008 Express Editions

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Moving from CS 61A Scheme to CS 61B Java

Mathematical Induction

1 Description of The Simpletron

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Deitel Dive-Into Series: Dive Into Microsoft Visual C++ 6

JavaScript: Control Statements I

Visual Basic Programming. An Introduction

Computer Programming In QBasic

Java Basics: Data Types, Variables, and Loops

Demonstrating a DATA Step with and without a RETAIN Statement

Quick Tricks for Multiplication

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Pre-Algebra Lecture 6

Object Oriented Software Design II

Order of Operations More Essential Practice

Athena Knowledge Base

Repetition Using the End of File Condition

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Math: Study Skills, Note Taking Skills, And Test Taking Strategies

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Pseudo code Tutorial and Exercises Teacher s Version

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Transcription:

Common Beginner C++ Programming Mistakes This documents some common C++ mistakes that beginning programmers make. These errors are two types: Syntax errors these are detected at compile time and you won't be able to run your program until these are fixed. Listed are the errors that you will see if you are using the Visual Studio C++ compiler. Syntax errors will be displayed on the Output window. Here is a screen-shot with an error shown circled in red: Logic errors these are not compile errors, so your program will compile and run. However, it most likely won't give you the correct results. These can be difficult to track down. Each common mistake shows an example of the error and the correction (in red) that will fix the mistake. These examples came from several resources, including http://www.cprogramming.com/tutorial/common.html

Common Beginner C++ Programming Mistakes Syntax Errors Common Syntax Errors (detected at compile time) 1. Undeclared Variables cin >> x; "Huh? Why do I get this error?" 'x' : undeclared identifier The compiler doesn't know what x means. You need to declare it as a variable. (The 'x' will be replaced with your specific variable name.) cin >> x; Another common issue for undeclared variables/functions is misspelling a variable/function name or using the case of the letters inconsistently. Remember, C++ is case sensitive, so int Main() is not the same as In Visual Studio, if you enter Main() instead of main(), you get the following linker error: error LNK2019: unresolved external symbol _main referenced in function tmaincrtstartup 1

Common Beginner C++ Programming Mistakes Syntax Errors 2. Undeclared Functions menu(); void menu() "Why do I get an error about menu being unknown?" error C3861: 'menu': identifier not found The compiler doesn't know what menu() stands for until you've told it, and if you wait until after using it to tell it that there's a function named menu, it will get confused. Always remember to put either a prototype for the function or the entire definition of the function above the first time you use the function. void menu(); menu(); void menu()... 2

Common Beginner C++ Programming Mistakes Syntax Errors 3. Missing semicolons cin >> x "Huh? Why do I get an error?" error C2146: syntax error : missing ';' before identifier 'cout' The compiler sees the cin and cout lines as one line of code, since there is only one semicolon. In larger programs, a single missing semicolon can generate multiple cascading errors. Fix the first occurrence of it and recompile before wasting time trying to track down extraneous errors. Note that in your specific program, "cout" in the above example will be replaced with the first word from the statement following the one in your program with the missing ; cin >> x; 3

Common Beginner C++ Programming Mistakes Syntax Errors 4. Extra semicolons void menu(); menu(); void menu(); "Huh? Why do I get an error?" error C2447: '' : missing function header (old-style formal list?) Semicolons go at the end of complete statements. The following are not complete statements, so they don't get a semicolon: Function declarations #include lines if lines switch lines Some of these will cause syntax errors, some will cause logic errors. void menu(); menu(); void menu() removed ; 4

Common Beginner C++ Programming Mistakes Syntax Errors 5. Incorrect number of braces cin >> x; if (x == 5) "Huh? Why do I get an error?" fatal error C1075: end of file found before the left brace '' Braces are the "begin" and "end" around blocks of code. You must have a for every. Missing (or extra) braces can lead to a cascading number of errors. Hint: Fix the braces issue and recompile before chasing down extraneous errors. cin >> x; if (x == 5) 5

Logic Errors (detected at run time) 1. Uninitialized variables int count; while (count < 100) cout << count; count++; "Why doesn't my program enter the while loop?" In C++ variables are not initialized to zero. In the above snippet of code, count could be any value in the range of int. It might, for example, be 586, and in that situation the while loop's condition would never be true. Perhaps the output of the program would be to print the numbers from -1000 to 99. In that case, once again, the variable was assigned a memory location with garbage data that happened to evaluate to -1000. Visual Studio will give you the following warning, but will still let the compile succeed and will let you run the program. You should strive to fix all warnings in addition to all errors. warning C4700: uninitialized local variable 'count' used Remember to initialize your variables. int count = 0; while (count < 100) cout << count; count++; 6

2. Setting a variable to an uninitialized value int a, b; int sum = a + b; cout << "Enter two numbers to add: "; cin >> a; cin >> b; cout << "The sum is: " << sum; When Run: Enter two numbers to add: 1 3 The sum is: -1393 "What's wrong with my program?" Often beginning programmers believe that variables work like equations - if you assign a variable to equal the result of an operation on several other variables that whenever those variables change (a and b in this example), the value of the variable will change. In C++ assignment does not work this way: it's a one shot deal. Once you assign a value to a variable, it's that value until you reassign the values. In the example program, because a and b are not initialized, sum will equal an unknown random number, no matter what the user inputs. Visual Studio will give you a warning about referencing uninitialized variables. Heed the warning! To fix this error, move the addition step after the input line. int a, b; int sum; cout << "Enter two numbers to add: "; cin >> a; cin >> b; sum = a + b; cout << "The sum is: "<< sum; 7

3. Using a single equal sign to check equality char done = 'Y'; while (done = 'Y') cout << "Continue? (Y/N)"; cin >> done; "Why doesn't my loop ever end?" If you use a single equal sign to check equality, your program will instead assign the value on the right side of the expression to the variable on the left hand side, and the result of this statement is TRUE. Therefore, the loop will never end. Use == to check for equality. char done = 'Y'; while (done == 'Y') cout << "Continue? (Y/N)"; cin >> done; 8

4. Extra Semicolons for (x = 0; x < 100; x++); "Why does it just output 100?" You put in an extra semicolon. Remember, semicolons don't go after if statements, loops, or function definitions. If you put one in any of those places, your program will function improperly. for (x = 0; x < 100; x++) removed ; This is also a common mistake with a while statement, an if statement, and a switch statement. 9

5. Forgetting a break in a switch statement int x = 2; switch(x) case 2: cout << "two" << endl; case 3: cout << "three" << endl; "Why does it print two and three?" Remember that C++ does not break out of a switch statement when a case is encountered. It only breaks out when it hits the break; statement. int x = 2; switch(x) case 2: cout << "two" << endl; break; case 3: cout << "three" << endl; break; // in case more cases are added later 10

6. Overstepping array boundaries int array[10]; for (int x = 1; x <= 10; x++) cout << array[x]; "Why doesn't it output the correct values?" Arrays begin indexing at 0; they end indexing at length-1. For example, if you have a ten element array, the first element is at position zero and the last element is at position 9. int array[10]; for (int x = 0; x < 10; x++) cout << array[x]; 11

7. Misusing the && and operators int value; do value = 10; while(!(value == 10)!(value == 20)) "Huh? Even though value is 10 the program loops. Why?" Consider the only time the while loop condition could be false: both value==10 and value==20 would have to be true so that the negation of each would be false in order to make the operation return false. In fact, the statement given above is a tautology; it is always true that value is not equal to 10 or not equal to 20 as it can't be both values at once. Yet, if the intention is for the program only to loop if value has neither the value of ten nor the value of 20, is necessary to use && :!(value==10) &&!(value==20), which reads much more nicely: "if value is not equal to 10 and value is not equal to 20", which means if value is some number other than ten or twenty (and therein is the mistake the programmer makes - he reads that it is when it is "this" or "that", when he forgets that the "other than" applies to the entire statement "ten or twenty" and not to the two terms - "ten", "twenty" - individually). A quick bit of boolean algebra will help you immensely:!(a B) is the equivalent of!a &&!B (Try it and see). The sentence "value is other than [ten or twenty]" (brackets added to show grouping) is translatable to!(value==10 value==20), and when you distribute the!, it becomes!(value==10) &&!(value==20). The proper way to rewrite the program: int value; do value = 10; while (!(value == 10) &&!(value == 20)) 12