Bob5421
Bob5421

Reputation: 9073

Strange c pointer issue

I had this kind of question in a job interview. This code seems to be very easy:

  long a = 1234;
  long &b = a;

For me, a and b are the same thing. But i was asked which expression of the 4 following is the same thing

  const *long c = &a;
  const long *d = &a;
  const * long e = &a;
  long *const f = &a;

Honestly, i do not understand which of the 4 is the equivalent.

Upvotes: 3

Views: 120

Answers (4)

Teivaz
Teivaz

Reputation: 5665

The thing here is that reference can not be assigned to point to another object once initialized. So the closest analogy to pointers would be a constant pointer to non-constant object. Thus you just need to find an expression which matches:

const *long c = &a; // invalid
const long *d = &a; // non-const pointer to const long
const * long e = &a; // invalid
long *const f = &a; // const pointer to non-const long

Upvotes: 4

Zen
Zen

Reputation: 5500

I think all of you forget to mention the principle of C declaration: you should read it from right to left unless it is surrounded by parenthesis.

const *long c // c is a long of const pointer, wtf?
const long * d // d is a pointer to a const long, good
const * long e // space doesn't matter in C
long * const f // f is a const pointer to long, good

Upvotes: 0

nosbor
nosbor

Reputation: 2999

Let's check that code:

  long a = 1234; // you declare variable and initialize with 1234 value
  long &b = a;   // you declare another variable that points to the same address as a

In that case if you print both you will see that both has the same address and value:

  a = 555;
  printf("%d, %d, %d, %d\n", a, &a, b, &b); \\ a and b are 555

But you cannot change the address of b (of a also). Taking all of the above into account you can assume that the fourth option is correct answer as you also cannot change the address of this pointer.

  long *const f = &a;

Upvotes: 0

ilotXXI
ilotXXI

Reputation: 1085

  1. Invalid syntax.
  2. Pointer to constant object. The pointer address can change, data cannot.
  3. Invalid syntax.
  4. The last one is a constant pointer to non-constant object. Like a reference to non-const.

Upvotes: 1

Related Questions