Friday 18 November 2011

Predict the output or error(s) for the following:

const int size = 5;

void print(int *ptr)

{

cout<<ptr[0];


}

void print(int ptr[size])

{

cout<<ptr[0];


}

void main()

{

int a[size] = {1,2,3,4,5};


int *b = new int(size);


print(a);


print(b);


}

Answer:

Compiler Error : function 'void print(int *)' already has a body

Explanation:

Arrays cannot be passed to functions, only pointers (for arrays, base addresses) can be passed. So the arguments int *ptr and int prt[size] have no difference as function arguments. In other words, both the functoins have the same signature and so cannot be overloaded.

2 comments: