Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default parameter of a function as an array [duplicate]

Possible Duplicate:
Default values for array arguments

How do I give an array as the default parameter to a function? I tried this:

void drawCircle(float radius, GLfloat colour[3]={2.0, 3.0, 4.0}, bool do=true) {
...
}

The part GLfloat colour[3]={2.0, 3.0, 4.0} gives me an error. Is this possible in C++?

like image 705
Carven Avatar asked Dec 04 '22 20:12

Carven


2 Answers

In C++, You cannot pass a complete block of memory by value as a parameter to a function, but You are allowed to pass its address.

So NO, you cannot do that atleast in C++03.

You can do this:

GLfloat defaultColor[3] = {2.0, 3.0, 4.0}; 

void drawCircle(float radius, GLfloat colour[3]= defaultColor, bool do=true)
{
}
like image 125
Alok Save Avatar answered Feb 19 '23 12:02

Alok Save


You cannot pass an array by value, and so you cannot do that.

So the workaround is, overload the function as:

void drawCircle(float radius, GLfloat *colour, bool pleaseDo) 
{
  //...
}
void drawCircle(float radius, GLfloat *colour)
{
  drawCircle(radius, colour, true);
}
void drawCircle(float radius) 
{
   GLfloat colour[3]={2.0, 3.0, 4.0};
   drawCircle(radius, colour, true);
}

drawCircle(a,b,c); //calls first function
drawCircle(a,b);   //calls second function
drawCircle(a);     //calls third function

Second and third function eventually call the first function!

Also note that do is a keyword, so you cannot use it as variable name. I replaced it with pleaseDo :D

like image 24
Nawaz Avatar answered Feb 19 '23 10:02

Nawaz