GeeksforGeeks » Interview Questions

how to debug the c code............?

(5 posts)
  • Started 3 months ago by sanjeev
  • Latest reply from rajeevpodar

Tags:

  1. sanjeev
    Member
    Posted 3 months ago #

    unsigned int a, b, c;
    /* a and b are assume to have some values */
    c = (a + b) / 2; // <- There is a bug in this st
    What is the bug? and how you debug it?

  2. kartik
    Moderator
    Posted 3 months ago #

    There are few things to note about your program.

    1) a,b and c are not initialized.
    2) The statement "c = (a + b) / 2" may cause overflow for large values of a and b.

    To debug the code, you can add watches for the variables you want to trace.

  3. Abhijeet Deshpande
    Member
    Posted 3 months ago #

    I cannot see any bug other than what karthik commented. You typecast appropriately to get float values upon division. But that would be a semantic error and not a bug.

  4. DJ
    Member
    Posted 3 months ago #

    it will result in overflow..to avoid this use
    c=a + (b-a)/2;

  5. Rajiv
    Member
    Posted 3 months ago #

    @Dj:

    It will fail for negative values e.g.
    a = 20, b = -10;

    The output should be 5
    But in your case

     c = a + (b-a)/2
    

    O/P will be : -5


Reply

You must log in to post.

RSS feed for this topic