2

Using 2 facts about C,

  1. In C programming, an integer pointer will point to an integer value whose address is provided to the pointer.

  2. And in pass by reference, we are actually passing the original variable's address to a function.

so, is the following acceptable :

    #include<stdio.h>

    void square(int *p)
    {
        *p = (*p)*(*p);
    }

    int main()
    {
        int var = 10;
        square(&var);       // Address of the variable
        printf("\nSquared value : %d",var);
        
        return 0;
    }

Though this is doing the same work (if not wrong) as the following :

    #include<stdio.h>

    void square(int *p)
    {
        *p = (*p)*(*p);
    }

    int main()
    {
        int var = 10;
        int *ptr;
        ptr = &var;
        square(ptr);       // Pointer as the argument
        printf("\nSquared value : %d",var);
        
        return 0;
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    They're equivalent. If you don't need the pointer for anything else, there's no need to create the variable `ptr`. – Barmar Jun 16 '22 at 19:27
  • IMO the first way is better because it is clear what you are doing -- in the 2nd way it is possible the program could be modified to move the assignment of ptr far from the use of it making it less clear. – Hogan Jun 16 '22 at 19:28
  • just fyi, in your second example you could also do `printf("\nSquared value : %d", *ptr);` to further verify `ptr` points to `var`. – yano Jun 16 '22 at 19:31
  • okay great, just needed opinions on this one. – Free_loader Jun 16 '22 at 19:33
  • 1
    One more thing, I recommend moving your (or adding a) newline in `printf` to the end: `printf("Squared value : %d\n",var);`. `stdout` is line buffered, so it won't dump its output until it sees a newline. You immediately return which flushes it anyway, but in a bigger program that may not be the case and you could end up in a situation where you're scratching your head wondering why there's no output. See https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – yano Jun 16 '22 at 19:36
  • And a small advertisement to the end: if you have code that already does what it should, and you want to get a review on it, ask on https://codereview.stackexchange.com/, where you get additional hints on stylistic issues. – Roland Illig Jun 16 '22 at 19:45

1 Answers1

3

In both cases you're passing the address of var to the function, so both are fine.

dbush
  • 205,898
  • 23
  • 218
  • 273