Friday 14 December 2012

Return of C Test Part 2

... and I got 58.5 marks out of 61, 95%! Nice one!

For those interested, I managed to find some a unit test harness for C:

http://cunit.sourceforge.net

Careful with the spelling, chaps.

Pop quiz! Why does the following produce 47 rather than 144 (7 + 5)2? And what would you do to correct it?

#include <stdio.h>

#define FIRST_PART      7 
#define LAST_PART       5 
#define ALL_PARTS       FIRST_PART + LAST_PART 

int main() { 
    printf("The square of all the parts is %d\n", 
        ALL_PARTS * ALL_PARTS); 
    return (0);
}

Answers in the comments.

1 comment:

  1. Remember that define is literal, so ALL_PARTS * ALL_PARTS comes out as 7 + 5 * 7 + 5. Well, if you remember operator precidence, this is 7 + 35 + 5, which is 47, rather than 12 * 12. To get around this, change the definition of all parts to #define ALL_PARTS (FIRST_PART + LAST_PART).

    ReplyDelete