Can someone please explain why do the following lines exist in speller.c enter image description here

I do know what #undef does but why is it used here?

I think this is an incorrect use of #undef because calculate and getrusage are functions used in the program not something that is #defined.


Back in the 2012 Harvard on-campusCS50, or the CS50x lectures for the 2013 class, David Malan mentioned that the person who was in the lead on the leader-board had used a trick in order to get to the top.

So in combination with the not really logical #undefs for the functions used to time the execution of the speller operations I'd say the reason for those #undefs is to prevent students from overwriting the functions in speller.c using some #defines in order to trick the execution timing used in the problem set.

| improve this answer | |
  • So this means that #undef can even be used to undefine functions. Am I right? – user1529 Jan 18 '15 at 11:07
  • 1
    @user1529 not really. The point is to prevent someone from defining macros with the same names as these functions in order to show off fake run-times. Having these #undefs in speller.c guarantees that any such macros are undefined. – Kareem Jan 18 '15 at 12:08
  • 1
    Oh, ok! So it's like a safety measure that the results generated by the benchmark functions will be true and not hacked by some #define constants using the same name? – theodor Oct 21 '16 at 8:01
  • I understand this reasoning, but I wonder about the logic. For example, isn't getrusage defined in <sys/resource.h>? Does the #undef getrusage statement undefine them? – Chester Nov 6 '19 at 19:57
  • @Chester in C the #undef keyword is used to undefine a name previously defined with #define. You cannot #undef a function. The idea of #define is that the preprocessor goes through the code within your compilation unit and replaces that word - i.e. in the case of speller.c, the file dictionary.h gets included into your code and if you had a getrusage macro in there any call to getrusage would be replaced by your code. If you were to try something similar with a function the compiler would not compile as getrusage already is a function in the code (but not a preprocessor macro). – Andrej Jan 9 at 11:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .