Tips on common C++ Errors

Hey CEans,

When your writing a program in C++ and an error pops up when your compiling your program leaving you wondering what the error is and scratched your head, without knowing what the error says!!!!

Well if you had a situation like that before, you don't have to worry anymore!!!πŸ˜€

In this thread we will discuss about the types of errors and what the error means so that you can debug you program easily and giving you a clear picture of what made the error pop up. And you will get some tips too!! on how to avoid errors and improve your program.

I want you guys out there to help us too, just drop in the errors you have faced and we will give the answer why the error has occurred and translate to you what the compiler is trying to tell you!!

Hope you guys like this thread....
If you guys have any suggestions please post it across!!!! (I am waiting for your feedbacks;-))



-Arvind(Slashfear)

Replies

  • slashfear
    slashfear
    Here goes the first session on Errors:

    First lets know what are the types of errors, The most common errors can be broadly classified as follows:

    1. Programming errors
    These are generated when typographical errors are made by users.

    2. Compiler errors
    These are errors detected by the compiler that make the program un-compilable.

    3. Linker error
    These are errors generated when the executable of the program cannot be generated. This may be due to wrong function prototyping, incorrect header files.

    4. Execution error
    These errors occur at the time of execution. Looping and arithmetic errors falls
    under this category.

    5. Logical errors
    These errors solely depend on the logical thinking of the programmer and are easy to detect if we follow the line of execution and determine why the program takes that path of execution.


    Here is the list of some common programming errors:


    1. Misuse of the Include Guard. A common mistake is to use same symbol in multiple files for #ifndef.

    2. Typo's : Using ">" for ">>" and "<" for "<<"

    3. Trying to directly access the private variables in the main program.

    4. Switch Statements without break.

    5. Wrong usage of postfix and prefix operator (diff between i++ and ++i)

    6. Undeclared and Uninitialized Variables and functions.

    7. ALWAYS USE MAKE FILE if you have more than one C++ program. The order of compilations matters a lot too.

    8. Trying to include "INCORRECT" header function.

    9. Marking a member function as const in the class definition but not in the member function implementation.

    10. Returning a value in a void function.

    11. Confusing the name of an array with the contents of the first element.

    12. Cstring array Errors - Arr[10] = Arr[0] to Arr[9]. Trying to access Arr[10] element.

    13. Using "=" ( assignment operator ) instead of "= =" (comparison operators) scanf() without '&' and wrong format.(IN C)

    14. Trying to divide a number by Zero.

    15. Poor Loop Exiting comparisons will tend to either loop being not executed at all or goes to an infinite loop.

    16. Not using string functions and treating the strings are integer . Say trying to compare string by (string1= = string2) , rather than using strcmp command

    17. CString not terminated by '\0'- Null character

    18. Mismatched "{" or IF-ELSE statements or for that matter any looping statment.

    19.Namespace errors


    Avoid these common mistakes in your program and make your coding skill highπŸ˜‰
    Hope this info was useful!!!!😁

    More on Tips and how errors occur, coming soon.........
  • shalini_goel14
    shalini_goel14
    * Cool Tips man * 😁
  • slashfear
    slashfear
    Thanks!!!!😁 shalini

    Ok so here comes today's Error Tips....................

    Don't forget your semicolons!!! they cause the majority (at least in my case😁) of your compilation errors! below are examples of when to and when not to use semicolons...SEMICOLONS ARE AT THE END OF ALMOST ALL C++ LINES (but of course not all, there are exceptions)

    In the below code you will find that each and every line is commented for you guys to understand well..........;-) (Forgive me if it's shabby πŸ˜’)

    [SIZE=3][B]//Written by: Arvind(slashfear)  
    // Use of SemiColons!!!!!!!! 
     
    void myFUNCTION(int x) ; // semicolon after all prototypes 
     
    int main()        // no semicolon after a function definitions 
    {                // no semicolon after a opening brackets 
        int a ;        // semicolon after all variable declarations 
        a = 7 + 8 ; // semicolon after all defintions of a variable 
     
        cout << a << endl ;  // semicolon after all cout lines 
        cin >> a ;    // semicolon after all cin lines 
     
        int x = 7 ; 
        int y = 9 ; 
        if(x == y)    // no semicolon after if 
        { 
            cout << "HEY YOU!" << endl ; 
        } 
        else        // no semicolon after else 
        { 
            cout << "WUZ UP?!?!" << endl ; 
        } // no semicolon after a set of if-else statements 
     
        do    // no semicolon after do 
        { 
            cout << "Slashfear's Time!" << endl ; 
            y = y + 1 ; 
        }while(y < 12) ;  // semicolon after all do-while statements!!! 
     
        while(x == y)  // no semicolons after while 
        { 
            cout << "Dude, you rock!" << endl ; 
        } // no semicolons after while statements!!!!! 
     
        /* for loops... 
           for(delcaration ; condition ; incrementation) 
           semicolons go after the declaration and condition 
        */ 
        for(int u = 2 ; u < 12 ; u++)  // no semicolon after for 
            cout << u << endl ; 
     
        myFUNCTION(u) ; // semicolons after all function calls!! 
     
        return 0 ; // semicolons after all returns 
    } // no semicolons after closing brackets of a function 
     
    void myFUNCTION(int x) 
    { 
        cout << "x rules! x is " << x << endl ; 
    } 
     
    struct date // no semicolon after struct line 
    { 
        int month ; 
        int day ; 
        int year;  
    };  // semicolon after all structs!!!!!!!! 
     
    class cheese{  // no semicolon after class line 
    private: 
        int x ; 
    public: 
        cheese() ; 
        void function1() ; 
    };  // semicolon after all classes!!!!!![/B][/SIZE]
    
    Remember to put your semicolons in appropriate places, Hope this info was useful for you guys...........πŸ˜‰

    -Arvind(slashfear)
  • slashfear
    slashfear
    Hey guys,

    Here are some more tips on errors........

    Compiler Errors

    undeclared identifier


    1. Example doy.cpp: In function `int main()': doy.cpp:25: `DayOfYear' undeclared (first use this function) doy.cpp:25: (Each undeclared identifier is reported only once for each function it appears in.) doy.cpp:25: parse error before `;' token
    2. Meaning
    You used "DayOfYear" in your code, but the compiler has not seen a definition for "DayOfYear". It doesn't know what "DayOfYear" is.
    3. Usual Causes
    1. You forgot to include the header file that defines the class/struct/function/etc
    2. You misspelled the name of the identifier

    cout undeclared

    1. Example xyz.cpp: In function `int main()': xyz.cpp:6: `cout' undeclared (first use this function) xyz.cpp:6: (Each undeclared identifier is reported only once for each function it appears in.)
    2. Meaning
    This is really a special case of "undeclared identifier".
    3. Usual causes
    1. You forgot to include
    2. You forgot "using namespace std;"

    jump to case label

    1. Example switch.cpp: In function `int main()': switch.cpp:14: jump to case label switch.cpp:11: crosses initialization of `int y'
    2. Meaning
    Your code tried to jump to a case label
    3. Usual Causes
    1. You declared a variable within a "case" inside a switch. This error is fixed by enclosing your code for the case inside of braces.

    discards qualifier

    1. Example myfile.cpp: In function `int main()': myfile.cpp:20: passing `const DayOfYear' as `this' argument of `void DayOfYear::Set(int, int)' discards qualifiers
    2. Meaning
    You have an inconsistency with the use of "const"
    3. Usual Causes
    1. A non-const member function is being invoked for a const object
    2. A const object is being passed as a non-const parameter
    3. A const member function calls a non-const member function
    4. See the CMSC 202 lecture notes on the use of const


    I really don't know are these tips useful for you guys πŸ˜• ....... please reply if its useful or if its not useful I can stop posting right........πŸ˜‰ instead of wasting my time........😁

    -Arvind(slashfear)
  • silverscorpion
    silverscorpion
    hey, come on. These are of course useful. please continue.

    btw, I'm not quite clear about a few things.

    1) What is parse error?
    2) What is the significance of "using namespace std"
    3) I don't get the jump to label error. Pls explain.
    $) Also provide an example for "discards qualifier" error.
  • slashfear
    slashfear
    Hey scorpion,

    Hmmm I am glad that at least you are interested ........😁


    The following posts will make you clear buddy............πŸ˜‰
  • slashfear
    slashfear
    Hey Scorpion,

    Let me explain "Parse error" and significance of "using namespace std" First,

    Parse error:

    The compiler found a symbol that it wasn't expecting or that it thinks is missing. For example, an extra parentheses in any complex block of code, a semicolon placed inappropriately, a semicolon omitted from the previous line, etc..

    Important Note: The error is not always on the line mentioned by your compiler, but may be on some previous line. πŸ˜‰


    using namespace std:

    "using namespace std" make your work simpiler that is...let me explain, you include #include header file in your program to use the cin, cout endl etc... right, so let us take the below code as example:

    [B]
    #include
    
    int main()
    {
    char name[10];
    cout<<"Enter your name: "<>name;
    cout<<"Welcome to CE " <So what happens when you compile it..?? You will be getting an error stating:

    "error: β€˜cout’ was not declared in this scope"
    "error: β€˜cin’ was not declared in this scope"
    "error: β€˜endl’ was not declared in this scope"

    So to rectify this error there are two ways as shown below (one using namespace and another without using namespace):

    [B]// without using namespace 
    
    #include
    
    int main()
    {
    char name[10];
    std::cout<<"Enter your name: "<>name;
    std::cout<<"Welcome to CE " <
    [B]// by using namespace 
    
    #include
    using namespace std;
    int main()
    {
    char name[10];
    cout<<"Enter your name: "<>name;
    cout<<"Welcome to CE " <So namespaces allows us to group a set of global classes, objects and/or functions under a name. If you specify using namespace std then you don't have to put std:: throughout your code. The program will know to look in the std library to find the object. Namespace std contains all the classes, objects and functions of the standard C++ library. 

    And by using "using namespace std" you save time 😁


    Hope it was clear if you still got any doubts, ask me ........πŸ˜‰

    -Arvind(slashfear)
  • slashfear
    slashfear
    Hey Scorpion,

    Here is the explanation for Jump to case label and Discards qualifier

    Jump to case label:

    Ok I think you can understand from the example shown below:

    The following is not allowed:
    [B]switch (a)
    {
    case 1:
    int a = 6;
    //stuff
    break;
    
    case 2:
    //stuff
    break;
    }[/B]
    
    The following is allowed:
    [B]switch (a)
    {
    case 1:
    {
    int a = 6;
    //stuff
    }
    break;
    
    case 2:
    //stuff
    break;
    }[/B]
    
    If you still dint get it...Here when you are using a switch statement and you have more than one line of instruction you have to enclose it in parantheses { and } or it would cause "jump to case label"


    Discards qualifier:


    When you use constant method to call a non-constant method that is const does not allow the function to call non-const methods of the class and will lead to discard qualifier.

    Since you need an example here it is.....

    Consider a function, f, which takes a non-const argument something as shown below:
      [B] double f( double& d );
    [/B]
    Say you wish to call f from another function g as shsown below:
     [B]
       void g (const double& d)
       {
         val = f(d);
       }[/B]
    
    So when you try to do this you will get a discards qualifier error, Because d is const and should not be modified, the compiler will complain because f may potentially modify its value. To get around this dilemma, use a const_cast (One type of type casting) as shown below:
    [B]void g (const double& d)
       {
          val = f(const_cast(d));
       }[/B]
    
    This strips away the ``const-ness'' of d before passing it to f. You cannot use const_cast for any other types of casts, such as casting a base class pointer to a derived class pointer (you have another type of type casting to do this ). If you do so, the compiler will report an error.



    Hope cleared your doubts buddy......;-) if you have doubts still..... you can ask

    and stay connected to get more info on ERRORS........😁
  • silverscorpion
    silverscorpion
    That was good. Now it's clear.
    Thanks buddy!!
  • Saandeep Sreerambatla
    Saandeep Sreerambatla
    Great Tips not read all but read few tips and good.

    Thanks , please continue this is very useful..
  • slashfear
    slashfear
    Hey guys,

    Thanks for the support ES and scorpion😁
  • slashfear
    slashfear
    Hi guys,

    Here we go again, new Tips.........


    Multi-line string / untermainated string


    1. Example This short program
    #include 
    #include 
    using namespace std;
    int main( )
    {
       cout << "Slash is my buddy;
       cout << " and so is Fear" << endl;
    }
    
    
    causes these compiler errors string.
    cpp:7:12: warning: multi-line string literals are deprecated string.cpp: In function `int main()':
    string.cpp:7: `so' undeclared (first use this function) string.cpp:7: (Each undeclared identifier is reported only once for each function it appears in.) string.cpp:7: parse error before `Mary' string.cpp:8:28: warning: multi-line string literals are deprecated string.cpp:8:28: missing terminating " character string.cpp:7:12: possible start of unterminated string literal

    Or when your using an advanced compiler it would throw you the following error:

    cpp:6: error: missing terminating " character

    2. Meaning
    The compiler thinks that you are trying to create a multi-line string which is no longer a supported feature of the language

    3. Usual Causes
    1. You're missing a quote mark at the end of one of your strings





    Comparison between signed and unsigned integer expressions

    1. Example xyz.cpp: In function `int main()': zyz.cpp:54: warning: comparison between signed and unsigned integer expressions

    2. Meaning
    This is a compiler warning that you are comparing ( ==, <, > etc) an integer expression (may be poitive, negative or zero) and an unsigned integer expression (may be positive or zero, but not negative).

    3. Usual Causes

    1. In our projects, this warning usually arises in a for-loop which is looping through all elements of a vector. For example, assuming "grades" is a vector of some kind, the warning is generated by this code
    for (int i = 0; i < grades.size( ); i++
    { 
    // body of the for-loop here 
    } 
    
    because vector's size( ) function returns an unsigned int. To fix this problem simply define 'i' as an unsigned int too, as in
    for( unsigned int i; i < grades.size( ); i++)



    Suggest parentheses around assignment used as truth value

    1. Example xyz.cpp: In function `int main()': xyz.cpp:54: warning: suggest parentheses around assignment used as truth value.

    2. Meaning
    This is a suggestion from the compiler that you add parenthesis around an assignment statement that used as a condition in an if/while/for, etc. This is usually NOT what you meant to do.

    3. Usual Causes
    1. This warning is usually caused by using "=" instead of "==" in an if-statement as in
    if ( length = maxLength ) /* when what you meant was as shown below */
    if ( length == maxLength)



    Guys any doubts please ask!!!!😁

    Next would be various Pitfalls in C++.........;-)

    -Arvind(slashfear)
  • slashfear
    slashfear
    Hi Guys,

    This time we are going to go through the varies pitfalls will coding in C++, So lets get started....


    What is a pitfall?

    C++ code that

    -> compiles
    -> links
    -> runs
    -> does something different than you expect

    Example:

    if (-0.5 <= x <= 0.5) return 0;


    Pitfall:

    if (-0.5 <= x <= 0.5) return 0;

    This expression does not test the mathematical condition

    -1.5 <= x <= 1.5

    Instead, it first computes -0.5 <= x, which is 0 or 1, and then compares the result with 0.5.

    Bottom Line: Even though C++ now has a bool type, Booleans are still freely convertible to int.

    Since bool->int is allowed as a conversion, the compiler cannot check the validity of expressions. In contrast, the Java compiler would flag this statement as an error.



    Constructor pitfalls

    Example:

    int main()
    { string a("Hello");
    string b();
    string c = string("World");
    // ...
    return 0;
    }


    Pitfall:

    string b();

    This expression does not construct an object b of type string. Instead, it is the prototype for a function b with no arguments and return type string.

    Bottom Line: Remember to omit the ( ) when invoking the default constructor.

    The C feature of declaring a function in a local scope is worthless since it lies about the true scope. Most programmers place all prototypes in header files. But even a worthless feature that you never use can haunt you. 😁



    More Pitfalls to come......πŸ˜‰


    -Arvind(slashfear)
  • silverscorpion
    silverscorpion
    Good info.

    Is a pitfall the same as logical error? Can they be considered the same??
  • slashfear
    slashfear
    Hi scorpion,

    Thanks buddy :smile:

    Yes Pitfalls are Logical errors

    More Tips to come ........;-)

    -Arvind(slashfear)
  • bradkal
    bradkal
    Thank you for giving helpful tips on C++.
  • slashfear
    slashfear
    Hi Bradkal,

    Thanks and hope you stay connected for more TIPS 😁
  • slashfear
    slashfear
    Hi Guys,


    Constructor pitfalls Cont....



    1) Example:

    template
    class Array
    {
    public:
    Array(int size);
    T& operator[](int);
    Array& operator=(const Array&);
    // ...
    };

    int main()
    { Array a(10);
    a[0] = 0; a[1] = 1; a[2] = 4;
    a[3] = 9; a[4] = 16;
    a[5] = 25; a = 36; a[7] = 49;
    a[8] = 64; a[9] = 81;
    // ...
    return 0;
    }

    Pitfall:

    a = 36;

    Surprisingly, it compiles πŸ˜’:

    a = Array(36);

    a is replaced with a new array of 36 numbers.

    Bottom Line: Constructors with one argument serve double duty as type conversions.

    Avoid constructors with a single integer argument! Use the explicit keyword if you can't avoid them




    2) Example:

    template
    class Array
    {
    public:
    explicit Array(int size);
    // ...
    private:
    T* _data;
    int _size;
    };

    template
    Array::Array(int size)
    : _size(size),
    _data(new T(size))
    {}

    int main()
    { Array a(10);
    a[1] = 64; // program crashes
    // ...
    }

    Pitfall:

    template
    Array::Array(int size)
    : _size(size),
    _data(new T(size)) // should have been new T[size]
    {}

    Why did it compile πŸ˜’? πŸ˜•

    new T(size)

    returns a T* pointer to a single element of type T, constructed from the integer size.

    new T[size]

    returns a T* pointer to an array of size objects of type T, constructed with the default constructor.

    Bottom Line: Array/pointer duality is dumb, but unfortunately pervasive in C and C++.

    The Java compiler would catch this--Java, like most programming languages, supports genuine array types.

    More Constructor Pitfalls to come..........;-)

    -Arvind(slashfear)
  • slashfear
    slashfear
    Hi Guys,

    It's has been a long time..... πŸ˜’ I posted Tips in this section, So here we go....., Constructor pitfall cont....:smile:

    3) Example:

    template
    class Array
    {
    public:
    explicit Array(int size);
    // ...
    private:
    T* _data;
    int _capacity;
    int _size;
    };

    template
    Array::Array(int size)
    : _size(size),
    _capacity(_size + 10),
    _data(new T[_capacity])
    {}


    int main()
    { Array a(100);
    . . .
    // program starts acting flaky
    }

    Pitfall:

    Array::Array(int size)
    : _size(size),
    _capacity(size + 10),
    _data(new T[_capacity])
    {}

    Initialization follows the member declaration order, not the initializer order!

    Array::Array(int size)
    : _data(new T[_capacity])
    _capacity(_size + 10),
    _size(size),


    Tip:
    Do not use data members in initializer expressions.

    Array::Array(int size)
    : _data(new T[size + 10])
    _capacity(size + 10),
    _size(size),



    4) Example:

    class Point
    {
    public:
    Point(double x = 0, double y = 0);
    // ...
    private:
    double _x, _y;
    };
    int main()
    { double a, r, x, y;
    // ...
    Point p = (x + r * cos(a), y + r * sin(a));
    // ...
    return 0;
    }

    Pitfall:


    Point p = (x + r * cos(a), y + r * sin(a));

    This should be either

    Point p(x + r * cos(a), y + r * sin(a));

    or

    Point p = Point(x + r * cos(a), y + r * sin(a));

    The expression

    (x + r * cos(a), y + r * sin(a))

    has a legal meaning. The comma operator discards x + r * cos(a) and evaluates y + r * sin(a). The

    Point(double x = 0, double y = 0)

    constructor makes a Point(y + r * sin(a), 0).

    Bottom Line: Default arguments can lead to unintended calls. In our case, the construction Point(double) is not reasonable, but the construction Point() is. Only use defaults if all resulting call patterns are meaningful.


    More Tips and Pitfalls to come.........;-)


    -Arvind(slashfear)
  • tech..savy
    tech..savy
    hey slashfear....
    i didnt get the 4th example...
    why the comma discards the first argument and not the second....????
    can you please explain....

You are reading an archived discussion.

Related Posts

Hi friends, a few days back i heard that there are sites where we can find Java projects which are not completed but are left for us to complete. i...
I wanted your take on this guys. How many of us s take time out and decisively plan our careers ahead?
I am not sure how many of you are awared of it but cool information for people interested in robotics. right ? πŸ˜€ Check following links: Tokyo school to host...
CEans, We've successfully had meets in Pune, Mumbai, Hyderabad & Delhi. I think we can have better organization of our meets so that they are very useful and productive for...
​ Yes, technology tends to fall in price as it ages, but is the still-unreleased N97 prematurely getting on in the years or something? Did we miss that memo? Nokia...