C vs. C++ and C compiler optimization question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • John Goche

    #1

    C vs. C++ and C compiler optimization question

    /* Consider the following C snippet: */

    Foo *pFoo = NULL;

    void FooLength(Foo *pFoo);

    void FooHello(Foo **ppFoo);

    void FooWorld(Foo **ppFoo);

    void FooLength(Foo *pFoo) {

    int count = 0;

    for (Foo *p = pFoo; *p; p++)

    ++count;

    return count;

    }

    void FooHello(Foo **ppFoo) {

    int count = FooLength(*ppFo o);

    // ...

    }

    void FooWorld(Foo **ppFoo) {

    int count = FooLength(*ppFo o);

    // ...

    }

    // Consider the following C++ snippet:

    class FooHelloWorld {

    public:

    void FooHello(Foo **ppFoo) {

    iCount = FooLength(*ppFo o);

    // ...

    }

    void FooWorld(Foo **ppFoo) {

    // no need to recompute iCount

    // ...

    }

    private:

    void FooLength(Foo *pFoo) {

    int count = 0;

    for (Foo *p = pFoo; *p; p++)

    ++count;

    return count;

    }

    int iCount;

    Foo **ppFoo = NULL;

    };

    ----------------------------------------------------------

    We could have done the same in C by adding an extra global
    variable or function parameter. However, global variables
    tend to pollute, so in C we don't tend to keep too many
    of them, and too many function parameters can make a
    function too hard to understand. On the other hand
    in C++ we can place global variables inside classes
    so we can cache results easily without the need to
    pollute the global namespace or pass many
    arguments around.

    I wonder if the C compiler could notice that the same
    count value is being reused and automatically optimize
    by creating a global variable to hold the value
    returned from FooCount. My guess is that it
    cannot since it does not know whether the
    pFoo linked list will be changed between
    the invocations of FooHello and FooWorld.

    Regards,

    JG

  • Gianni Mariani

    #2
    Re: C vs. C++ and C compiler optimization question

    John Goche wrote:
    ....
    I wonder if the C compiler could notice that the same
    count value is being reused and automatically optimize
    by creating a global variable to hold the value
    returned from FooCount. My guess is that it
    cannot since it does not know whether the
    pFoo linked list will be changed between
    the invocations of FooHello and FooWorld.
    Try it and see.

    I'm not sure what find of functionality you're looking for but the best
    way to handle optimization is to first make sure you need to worry and
    then try a few different things to check how the compiler behaves.

    The few times I have needed to do an optimization I noticed that the
    compiler optimizer has some rather unexpected results.

    Comment

    Working...