2

There's an apparent discrepancy in the way pointers are used that I don't understand.

The following code is taken from Pointers in C: when to use the ampersand and the asterisk? :

void swap(int *x, int *y) {int tmp = *x; *x = *y; *y = tmp; }
...
int a = 1, b = 2;
printf("before swap: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("after swap: a = %d, b = %d\n", a, b);

The following code is taken from https://en.wikipedia.org/wiki/Typedef :

int do_math(float arg1, int arg2) {
    return arg2;
}

int call_a_func(int (*call_this)(float, int)) {
    int output = call_this(5.5, 7);
    return output;
}

int final_result = call_a_func(&do_math);

Here's what I don't understand:

In the first case, in order to counteract the effect of the referencing operator, the dereferencing operator is used with x and y, so in order to use them more-or-less the same way you'd use them without dereferencing if you hadn't passed them by reference, you use them with *'s. But in the second case, call_this isn't invoked using a dereferencing operator that counteracts the fact that it was passed by reference; i.e. it's not called as (*call_this)(5.5, 7).

Why would you use *'s to counteract the effect of passing by reference so you can use the thing more-or-less as you normally would in the case of variables but not in the case of functions?

Community
  • 1
  • 1
inhahe
  • 331
  • 1
  • 7
  • 1
    C does not support references, just pointers. C++ is a different language. And a "referencing operator" does not exist in C. – too honest for this site Mar 19 '16 at 19:28
  • 1
    I find your usage of the phrase "counteract" very confusing. There is no counteracting of anything here. I'd recommend you grab on of the books on [this list](http://stackoverflow.com/q/388242/2069064) and read through it to understand better what pointers are. – Barry Mar 19 '16 at 19:30
  • I guess my use of the word counteract was a little confusing. I just meant that if you pass a value by reference, you'll have to dereference it in order to use it normally, so the two are complementary. – inhahe Mar 19 '16 at 19:42

1 Answers1

2

You can call function pointers as well as functions:

void (*a)();
void (b)();

// Both valid
a();
b();
Daniel
  • 30,896
  • 18
  • 85
  • 139