Computing > Programming

creating a function but not always using all the arguments

(1/15) > >>

So if i write a function that has a number of input arguments but I don't use them all what happens? will they just be assumed as 0? i am sure i have seen this in Arduino library functions.

In C++ you indicate optional arguments by specifying default values.

For example...  int foo(int a, int b = 0, int c = 5, char * s = NULL);

The first argument has no default, so it is required. The others are optional. You can not skip an optional argument.

foo(1, , 3, "test");  <-- skip not allowed

foo(); <-- required argument missing

foo(1, 2);  <-- OK

So does this work in C?

Arguments are passed by value, that is a copy is taken and put on the stack. The function then takes the value from the stack.
Nothing will happen if you do not use the value.
The compiler may warn you that you have not used a variable.

Since variables are passed as copies, you cannot change input parameters from inside functions.
Instead, you have to pass in by reference. In other words, pointers.

Edit: no, C does not support default parameter values.

Both C and C++ support parameter specifiers 'const' which tells the compiler that the copy of variable on the stack cannot be changed.

C does supports varargs, but you get no compile time sanity checking, and no defaults without some extra work.

printf() is an example of a function that uses varargs


[0] Message Index

[#] Next page

There was an error while thanking
Go to full version