0

If i have a funtion int foo(const int A), am I allowed to do the following coding?

int (*Mypointer)(const int);
Mypointer = &foo;

In addition, am i also allowed to do the following which is without const in the declaration of the function pointer ?

int (*Mypointer)(int);
Mypointer = &foo;

Another interesting case is that, if I have int foo(int A) and I declare that

int(*Mypointer)(const int);
Mypointer = &foo;

I was given segmentation fault

4
  • 3
    Have you tried it? Commented Nov 4, 2021 at 18:38
  • I understand doubts about (2), but why would (1) be illegal? Commented Nov 4, 2021 at 18:38
  • Yes. Just tried it. I found that (1) and (2) both works. Another interesting case is that, if I have int foo(int A) and I declare that ``` int(*Mypointer)(const int); Mypointer = &foo; ``` I was given segmentation fault. I edited this case in the question Commented Nov 4, 2021 at 23:40
  • 1
    IMPORTANT NOTE: Violating "const" should give you a COMPILE error. Not necessarily a runtime "segmentation violation". Apples and oranges! Commented Nov 4, 2021 at 23:45

1 Answer 1

1

They should both work.

const applied to a parameter passed by value has an effect ONLY in function body, making it immutable there.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.