Search code examples
cpointerscomparisoninvocationindirection

Direct invocation vs indirect invocation in C


I am new to C and I was reading about how pointers "point" to the address of another variable. So I have tried indirect invocation and direct invocation and received the same results (as any C/C++ developer could have predicted). This is what I did:

int cost;
int *cost_ptr;

int main()
{
    cost_ptr = &cost;                          //assign pointer to cost
    cost = 100;                                //intialize cost with a value
    printf("\nDirect Access: %d", cost);
    cost = 0;                                  //reset the value
    *cost_ptr = 100;
    printf("\nIndirect Access: %d", *cost_ptr);
    //some code here

    return 0;                                  //1
}

So I am wondering if indirect invocation with pointers has any advantages over direct invocation or vice-versa? Some advantages/disadvantages could include speed, amount of memory consumed performing the operation (most likely the same but I just wanted to put that out there), safeness (like dangling pointers) , good programming practice, etc.
1Funny thing, I am using the GNU C Compiler (gcc) and it still compiles without the return statement and everything is as expected. Maybe because the C++ compiler will automatically insert the return statement if you forget.


Solution

  • Indirect and direct invocation are used in different places. In your sample the direct invocation is prefered. Some reasons to use pointers:

    • When passing a large data structure to a function one can passa pointer instead of copying the whole data structure.
    • When you want a function to be able to modify a variable in the calling function you have to pass a pointer to the original variable. If you pass it by value the called function will just modify a copy.
    • When you don't know exactly which value you want to pass at compile time, you can set a pointer to the right value during runtime.
    • When dynamically allocating a block of memory you have to use pointers, since the storage location is not known until runtime.