Slashdot Mirror


Optimizations - Programmer vs. Compiler?

Saravana Kannan asks: "I have been coding in C for a while (10 yrs or so) and tend to use short code snippets. As a simple example, take 'if (!ptr)' instead of 'if (ptr==NULL)'. The reason someone might use the former code snippet is because they believe it would result in smaller machine code if the compiler does not do optimizations or is not smart enough to optimize the particular code snippet. IMHO the latter code snippet is clearer than the former, and I would use it in my code if I know for sure that the compiler will optimize it and produce machine code equivalent to the former code snippet. The previous example was easy. What about code that is more complex? Now that compilers have matured over years and have had many improvements, I ask the Slashdot crowd, what they believe the compiler can be trusted to optimize and what must be hand optimized?" "How would your answer differ (in terms of the level of trust on the compiler) if I'm talking about compilers for Desktops vs. Embedded systems? Compilers for which of the following platforms do you think is more optimized at present - Desktops (because is more commonly used) or Embedded systems (because of need for maximum optimization)? Would be better if you could stick to free (as in beer) and Open Source compilers. Give examples of code optimizations that you think the compiler can/can't be trusted to do."

3 of 1,422 comments (clear)

  1. Bad example by nurd68 · · Score: 0, Redundant

    if(!ptr) is equivalent to if(ptr == 0)

    The problem is that there is nothing that says that NULL must be 0. Potentially, one could define NULL to be something else - like -1. Therefore, one should always use if(ptr == NULL).

    1. Re:Bad example by Webmonger · · Score: 1, Redundant

      I can't say whether the NULL macro is formally defined, but the null pointer is always 0, even if the bitwise machine representation is different.

  2. write clearer code first by Deadbolt · · Score: 1, Redundant
    Unless your benchmarks show that writing:
    if (!ptr) { ...
    saves you significant time/size from using:
    if (ptr == NULL) { ...
    write the clearer code, which is the second option.
    --
    "Honey, it's not working out; I think we should make our relationship open-source."