0

I know that putting const before p's type protects the object that p points to, but what about:

void f(int * const p)

Is such a declaration legal?

Also, what is the difference between the following:

  1. void f(const int *p)
  2. void f(int * const p)
  3. void f(const int * const p)
  4. void f(int const *p)
rrz0
  • 2,182
  • 5
  • 30
  • 65
  • 1
    You forget one case: `void f(int const *p)`, which is the same as `void f(const int *p)`. – Some programmer dude Mar 22 '18 at 10:14
  • Thanks, I will edit the question to include this case. – rrz0 Mar 22 '18 at 10:18
  • @Rrz0; Why do you think this question should be asked again? Did you not find similar questions and answers on SO? Do you think answers on other questions didn't explain the topic well? If you have better explanations then don't you think you can post it as an answer on other similar posts? – haccks Mar 22 '18 at 10:24

1 Answers1

3

Is such a declaration legal?

Yes, although the effect isn't the same as if const precedes p's type.

Also, what is the difference between the following:

  1. void f(const int *p)

    Putting const before p's type protects the object that p points to.

    Example:

    void f(const int *p) {
       int j;
    
       *p = 0;       //WRONG
       p = &j;       //legal
    }
    
  2. void f(int * const p)

    Putting const after p's type protectsp itself.

    Example:

    void f(int * const p) {
       int j;
    
       *p = 0;       //legal
       p = &j;       //WRONG
    }
    

    This feature isn't used very after since p is merely a copy of another pointer, there's rarely any reason to protect it. An even greater rarity is the next case.

  3. void f(const int * const p)

    Here const is protecting both p and the object it points to.

    Example:

    void f(const int * const p) {
       int j;
    
       *p = 0;       //WRONG
       p = &j;       //WRONG
    }
    
  4. void f(int const *p)

    This is the same as void f(const int *p). See point 1.

rrz0
  • 2,182
  • 5
  • 30
  • 65