Page 1 of 1

Default "C" subroutine values

Posted: Thu Nov 07, 2013 5:35 pm
by jwzumwalt
I am writing a routine library for VG graphics.
Is there a way in "C" to mimic how PHP allows default values for a subroutine call.

Suppose I have a subroutine for writing a Point at x,y with a color.
If the call is made without a color, I would like a default color to be assigned.

PHP example
call routine without color
Pointxy(x,y,) // notice missing color

php subroutine definition
Pointxy(x,y, color="black"); // php sub will assign "black" if value not passed

Can this be done in "C"?

Re: Default "C" subroutine values

Posted: Thu Nov 07, 2013 5:36 pm
by joan
No.

Re: Default "C" subroutine values

Posted: Thu Nov 07, 2013 5:49 pm
by r4049zt
Yes, by adding a couple of extra lines with an 'IF' to test values before your subroutine call and replace with defaults if not sensible. You can always write a new subroutine to hide those extra checks and call the old one.

Re: Default "C" subroutine values

Posted: Thu Nov 07, 2013 7:28 pm
by Janq
In C, no. In C++ yes:

Code: Select all

void Pointxy(int x, int y, unsigned int colour=0)
{
}

void ...some function...
{
    Pointxy(5,6);   // results in x=5, y=6, colour=0
    Pointxy(3,4,0x10203040);
}
(assuming colour is passed as an 8:8:8:8 packed integer - same thing works for any type though).

Re: Default "C" subroutine values

Posted: Mon Nov 11, 2013 3:44 am
by jwzumwalt
Thanks for the feedback. I thought I had subscribed to the question to receive email feedback but apparently did not do that.
Once again, thanks for the answers :)