Mark S.
Mark S.

Reputation: 301

Does const apply to all parameters passed into a function?

Given the following:

void abc(const int*, int*);
int x = 1;
int y = 2
abc(&x, &y);

Without knowing the definition of abc(), is there anyway of knowing what the values of x and y are after line 3 is executed?

This is what I believe to be true inside abc(),

x is a constant pointer that points to an int, therefore the value that is pointed to cannot change but the address that x points to CAN be changed. Is that correct?

Also, does the const in the function header apply to only the first parameter? or does it apply to both?

Upvotes: 0

Views: 98

Answers (3)

Pete Becker
Pete Becker

Reputation: 76438

Without knowing the definition of abc(), is there anyway of knowing what the values of x and y are after line 3 is executed?

Sure. Read the documentation.

Upvotes: 1

Phillip Ngan
Phillip Ngan

Reputation: 16126

x is a constant pointer that points to an int, therefore the value that is pointed to cannot change but the address that x points to CAN be changed. Is that correct?

You read the type from right to left. So the first parameter is a pointer to a integer constant, and the second is a pointer to an integer. So I'd rewrite your statement as: x is a pointer to a const int, therefore the value that is pointed to cannot change because it is a const.

Also, does the const in the function header apply to only the first parameter? or does it apply to both?

The const applies to the first parameter and not to the second one. They are completely independent from each other.

Upvotes: 0

Jonathan Potter
Jonathan Potter

Reputation: 37192

void abc(const int* a, int *b)
{
    *a = 1; // error - not allowed, *a is const
    a = b; // allowed, a is non-const
    *b = 1; // allowed, *b is non-const
    b = a; // error - not allowed, can't assign non-const pointer to a const pointer
    int c;
    b = &c; // allowed
}

Upvotes: 1

Related Questions