User avatar
jwzumwalt
Posts: 44
Joined: Sun Aug 04, 2013 4:00 pm

Default "C" subroutine values

Thu Nov 07, 2013 5:35 pm

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"?
Last edited by jwzumwalt on Thu Nov 07, 2013 5:36 pm, edited 1 time in total.

User avatar
joan
Posts: 14887
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Default "C" subroutine values

Thu Nov 07, 2013 5:36 pm

No.

User avatar
r4049zt
Posts: 113
Joined: Sat Jul 21, 2012 1:36 pm
Contact: Website

Re: Default "C" subroutine values

Thu Nov 07, 2013 5:49 pm

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.

Janq
Posts: 36
Joined: Sat Jun 02, 2012 3:36 pm

Re: Default "C" subroutine values

Thu Nov 07, 2013 7:28 pm

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).

User avatar
jwzumwalt
Posts: 44
Joined: Sun Aug 04, 2013 4:00 pm

Re: Default "C" subroutine values

Mon Nov 11, 2013 3:44 am

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 :)

Return to “C/C++”