# Defining a method with default arguments in C

**URL:** <https://www.ruby-forum.com/t/defining-a-method-with-default-arguments-in-c/66612>\
**Category:** Ruby\
**Created:** [August 27, 2006, 9:19pm UTC](https://www.ruby-forum.com/t/defining-a-method-with-default-arguments-in-c/66612 "2006-08-27T21:19:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bct](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/6a8cbe/32.png) [@bct](https://www.ruby-forum.com/u/bct)\
**Post date:** [August 27, 2006, 9:19pm UTC](https://www.ruby-forum.com/t/defining-a-method-with-default-arguments-in-c/66612/1 "2006-08-27T21:19:11Z")

</div>

Hello,

How can I define a default argument value such as the following in c?

def foobar(arg=1)  
end

Thanks,  
Brian T.

---

<div class="post-metadata">

**Author:** ![bct](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/6a8cbe/32.png) [@bct](https://www.ruby-forum.com/u/bct)\
**Post date:** [August 27, 2006, 10:31pm UTC](https://www.ruby-forum.com/t/defining-a-method-with-default-arguments-in-c/66612/2 "2006-08-27T22:31:14Z")

</div>

Brian T. wrote:

> Hello,
> 
> How can I define a default argument value such as the following in c?
> 
> def foobar(arg=1)  
> end
> 
> Thanks,  
> Brian T.

Specify the number of arguments as -1 in rb\_define\_method:

rb\_define\_method(myclass, “method\_name”, meth\_fnc, -1);

In your method use rb\_scan\_args to scan the argument list. If you don’t  
get enough arguments, use the default values instead.

---

<div class="post-metadata">

**Author:** ![bct](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/6a8cbe/32.png) [@bct](https://www.ruby-forum.com/u/bct)\
**Post date:** [August 28, 2006, 2:37am UTC](https://www.ruby-forum.com/t/defining-a-method-with-default-arguments-in-c/66612/3 "2006-08-28T02:37:41Z")

</div>

Timothy H. wrote:

> > 
> 
> Specify the number of arguments as -1 in rb\_define\_method:
> 
> rb\_define\_method(myclass, “method\_name”, meth\_fnc, -1);
> 
> In your method use rb\_scan\_args to scan the argument list. If you  
> don’t get enough arguments, use the default values instead.

My earlier post was incomplete. I should’ve explained that you should  
define your method like this:

VALUE meth\_fnc(int argc, VALUE \*argv, VALUE self)  
{  
// stuff  
}

argv is a C array of VALUEs, one for each argument passed to the method.  
argc is the number of VALUEs in argv.

rb\_scan\_args takes argc and argv as arguments.
