1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
extern "C"
{
// IO
void printf (const char*, ...);
void puts (const char*);
int getchar ();
}
void Apple (long int &a)
{
a = 100;
}
void Banana (long int *b)
{
*b = 200;
}
int main ()
{
long int n = 67;
printf("n %i.\n", n);
Apple(n); // 'n' is a variable, but it is referenced in the argument already, so Apple() can change 'n' without (&n).
printf("n %i.\n", n);
Banana(&n); // Here, I have to use the reference operator to point to 'n', (&n).
printf("n %i.\n", n);
#if 0
// Wrong
long int* x, y; // 'y' won't be a pointer, even though this is written as-if each label should be a pointer. That's not true.
#endif
// Right
long int *x, *y; // Its best to always use the form '*label' because its just more sensible. As we now know, 'type* label, label;' won't automatically make all labels be a pointer.
x = new long int;
y = new long int;
Apple(*x); // Redundant illustration. De-referencing a pointer to use in a reference... lame.
Banana(y); // Banana() works directly with pointers. No redundance.
printf("x %i.\n", *x); // Need to dereference.
printf("y %i.\n", *y); // Need to dereference.
delete x;
delete y;
getchar();
return 0;
}
|