-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.texi
639 lines (513 loc) · 18 KB
/
functions.texi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
@c This is part of The GNU C Reference Manual
@c Copyright (C) 2008-2009 Free Software Foundation, Inc.
@c See the file gnu-c-manual.texi for copying conditions.
@c ----------------------------------------------------------------------------
@node Functions
@chapter Functions
@cindex functions
You can write functions to separate parts of your program into distinct
subprocedures. To write a function, you must at least create a function
definition. It is a good idea also to have an explicit function
declaration; you don't have to, but if you leave it out, then the
default implicit declaration might not match the function itself, and
you will get some compile-time warnings.
Every program requires at least one function, called @code{main}.
That is where the program's execution begins.
@menu
* Function Declarations::
* Function Definitions::
* Calling Functions::
* Function Parameters::
* Variable Length Parameter Lists::
* Calling Functions Through Function Pointers::
* The main Function::
* Recursive Functions::
* Static Functions::
* Nested Functions::
@end menu
@c ----------------------------------------------------------------------------
@node Function Declarations
@section Function Declarations
@cindex function declarations
@cindex declarations, function
You write a function declaration to specify the name of a function, a
list of parameters, and the function's return type. A function declaration
ends with a semicolon. Here is the general form:
@example
@group
@var{return-type} @var{function-name} (@var{parameter-list});
@end group
@end example
@var{return-type} indicates the data type of the value returned by the function.
You can declare a function that doesn't return anything by using the return
type @code{void}.
@var{function-name} can be any valid identifier (@pxref{Identifiers}).
@var{parameter-list} consists of zero or more parameters, separated by commas.
A typical parameter consists of a data type and an optional name for the
parameter. You can also declare a function that has a variable number of
parameters (@pxref{Variable Length Parameter Lists}), or no parameters using
@code{void}. Leaving out @var{parameter-list} entirely also indicates
no parameters, but it is better to specify it explicitly with @code{void}.
Here is an example of a function declaration with two parameters:
@example
@group
int foo (int, double);
@end group
@end example
If you include a name for a parameter, the name immediately follows the
data type, like this:
@example
@group
int foo (int x, double y);
@end group
@end example
The parameter names can be any identifier (@pxref{Identifiers}), and if you
have more than one parameter, you can't use the same name more than
once within a single declaration. The parameter names in the
declaration need not match the names in the definition.
You should write the function declaration above the first use of
the function. You can put it in a header file and use the @code{#include}
directive to include that function declaration in any source code files that
use the function.
@c ----------------------------------------------------------------------------
@node Function Definitions
@section Function Definitions
@cindex function definitions
@cindex definitions, function
You write a function definition to specify what a function
actually does. A function definition consists of information regarding
the function's name, return type, and types and names of parameters, along
with the body of the function. The function body is a series of statements
enclosed in braces; in fact it is simply a block (@pxref{Blocks}).
Here is the general form of a function definition:
@example
@group
@var{return-type}
@var{function-name} (@var{parameter-list})
@{
@var{function-body}
@}
@end group
@end example
@var{return-type} and @var{function-name} are the same as what you use
in the function declaration (@pxref{Function Declarations}).
@var{parameter-list} is the same as the parameter list used in the function
declaration (@pxref{Function Declarations}), except you
@emph{must} include names for the parameters in a function definition.
Here is an simple example of a function definition---it takes two integers as
its parameters and returns the sum of them as its return value:
@example
@group
int
add_values (int x, int y)
@{
return x + y;
@}
@end group
@end example
For compatibility with the original design of C, you can also specify
the type of the function parameters @emph{after} the closing
parenthesis of the parameter list, like this:
@example
@group
int
add_values (x, y)
int x, int y;
@{
return x + y;
@}
@end group
@end example
@noindent
However, we strongly discourage this style of coding; it can cause
subtle problems with type casting, among other problems.
@c ----------------------------------------------------------------------------
@node Calling Functions
@section Calling Functions
@cindex calling functions
@cindex functions, calling
You can call a function by using its name and supplying any needed parameters.
Here is the general form of a function call:
@example
@var{function-name} (@var{parameters})
@end example
A function call can make up an entire statement, or it can be used as a
subexpression. Here is an example of a standalone function call:
@example
@group
foo (5);
@end group
@end example
@noindent
In that example, the function @samp{foo} is called with the
parameter @code{5}.
Here is an example of a function call used as a subexpression:
@example
@group
a = square (5);
@end group
@end example
@noindent
Supposing that the function @samp{square} squares its parameter, the
above example assigns the value 25 to @code{a}.
If a parameter takes more than one argument, you separate parameters with commas:
@example
@group
a = quux (5, 10);
@end group
@end example
@c ----------------------------------------------------------------------------
@node Function Parameters
@section Function Parameters
@cindex function parameters
@cindex parameters, function
Function parameters can be any expression---a literal value, a value stored in
variable, an address in memory, or a more complex expression built by
combining these.
Within the function body, the parameter is a local copy of the value passed into
the function; you cannot change the value passed in by changing the local copy.
@example
int x = 23;
foo (x);
@dots{}
/* @r{Definition for function @code{foo}.} */
int foo (int a)
@{
a = 2 * a;
return a;
@}
@end example
@noindent
In that example, even though the parameter @code{a} is modified in the
function @samp{foo}, the variable @code{x} that is passed to
the function does not change. If you wish to use the function to change
the original value of @code{x}, then you would have to incorporate the
function call into an assignment statement:
@example
x = foo (x);
@end example
If the value that you pass to a function is a memory address (that is, a pointer), then you
can access (and change) the data stored at the memory address. This
achieves an effect similar to pass-by-reference in
other languages, but is not the same: the memory address is simply a
value, just like any other value, and cannot itself be changed. The
difference between passing a pointer and passing an integer lies in
what you can do using the value within the function.
Here is an example of calling a function with a pointer parameter:
@example
@group
void
foo (int *x)
@{
*x = *x + 42;
@}
@dots{}
int a = 15;
foo (&a);
@end group
@end example
@noindent
The formal parameter for the function is of type pointer-to-@code{int}, and we
call the function by passing it the address of a variable of type @code{int}. By
dereferencing the pointer within the function body, we can both see and change
the value stored in the address. The above changes the value of
@code{a} to @samp{57}.
Even if you don't want to change the value stored in the address, passing the
address of a variable rather than the variable itself can be useful if the
variable type is large and you need to conserve memory space or limit
the performance impact of parameter copying. For example:
@example
@group
struct foo
@{
int x;
float y;
double z;
@};
void bar (const struct foo *a);
@end group
@end example
@noindent
In this case, unless you are working on a computer with very large memory
addresses, it will take less memory to pass a pointer to the structure
than to pass an instance of the structure.
One type of parameter that is always passed as a pointer is any sort
of array:
@example
@group
void foo (int a[]);
@dots{}
int x[100];
foo (x);
@end group
@end example
@noindent
In this example, calling the function @code{foo} with the parameter @code{a}
does not copy the entire array into a new local parameter within @code{foo};
rather, it passes @code{x} as a pointer to the first element in @code{x}.
Be careful, though: within the function, you cannot use @code{sizeof} to determine
the size of the array @code{x}---@code{sizeof} instead tells you the size of the
pointer @code{x}. Indeed, the above code is equivalent to:
@example
@group
void foo (int *a);
@dots{}
int x[100];
foo (x);
@end group
@end example
@noindent Explicitly specifying the length of the array in the
parameter declaration will not help. If you really need to pass an
array by value, you can wrap it in a @code{struct}, though doing this
will rarely be useful (passing a @code{const}-qualified pointer is
normally sufficient to indicate that the caller should not modify the
array).
@c ----------------------------------------------------------------------------
@node Variable Length Parameter Lists
@section Variable Length Parameter Lists
@cindex variable length parameter lists
@cindex parameters lists, variable length
@cindex function parameter lists, variable length
You can write a function that takes a variable number of arguments; these are
called @dfn{variadic functions}. To do this, the function needs to have at
least one parameter of a known data type, but the remaining parameters are
optional, and can vary in both quantity and data type.
You list the initial parameters as normal, but then after that, use an
ellipsis: @samp{...}. Here is an example function prototype:
@example
int add_multiple_values (int number, ...);
@end example
To work with the optional parameters in the function definition, you need
to use macros that are defined in the library header file
@samp{<stdarg.h>}, so you must @code{#include} that file. For a
detailed description of these macros, see @cite{The GNU C
Library} manual's section on variadic functions.
@comment The above paragraph previously had a proper @ref tag to the
@comment GLIBC section in question, but it didn't seem to render
@comment properly, at least in HTML. Replacing with @cite for now;
@comment feel free to revisit later.
Here is an example:
@example
int
add_multiple_values (int number, ...)
@{
int counter, total = 0;
/* @r{Declare a variable of type @samp{va_list}.} */
va_list parameters;
/* @r{Call the @samp{va_start} function.} */
va_start (parameters, number);
for (counter = 0; counter < number; counter++)
@{
/* @r{Get the values of the optional parameters.} */
total += va_arg (parameters, int);
@}
/* @r{End use of the @samp{parameters} variable.} */
va_end (parameters);
return total;
@}
@end example
@c Need to describe how the default promotion rules are applied to the
@c parameters passed in the ``...''.
To use optional parameters, you need to have a way to know how many
there are. This can vary, so it can't be hard-coded, but if you
don't know how many optional parameters you have, then you could
have difficulty knowing when to stop using the @samp{va_arg} function.
In the above example, the first parameter to the @samp{add_multiple_values}
function, @samp{number}, is the number of optional parameters actually passed.
So, we might call the function like this:
@example
sum = add_multiple_values (3, 12, 34, 190);
@end example
The first parameter indicates how many optional parameters follow it.
Also, note that you don't actually need to use @samp{va_end} function.
In fact, with GCC it doesn't do anything at all. However, you might want
to include it to maximize compatibility with other compilers.
@xref{Variadic Functions, Variadic Functions, Variadic Functions, libc, The GNU C Library Reference Manual}.
@node Calling Functions Through Function Pointers
@section Calling Functions Through Function Pointers
@cindex function pointers, calling through
You can also call a function identified by a pointer. The
indirection operator @code{*} is optional when doing this.
@example
@group
#include <stdio.h>
void foo (int i)
@{
printf ("foo %d!\n", i);
@}
@end group
@group
void bar (int i)
@{
printf ("%d bar!\n", i);
@}
@end group
@group
void message (void (*func)(int), int times)
@{
int j;
for (j=0; j<times; ++j)
func (j); /* (*func) (j); would be equivalent. */
@}
void example (int want_foo)
@{
void (*pf)(int) = &bar; /* The & is optional. */
if (want_foo)
pf = foo;
message (pf, 5);
@}
@end group
@end example
@c ----------------------------------------------------------------------------
@node The main Function
@section The @code{main} Function
@cindex main function
@cindex function, main
Every program requires at least one function, called @samp{main}.
This is where the program begins executing. You do not need to write a
declaration or prototype for @code{main}, but you do need to define it.
The return type for @code{main} is always @code{int}. You do not have
to specify the return type for @code{main}, but you can. However, you
@emph{cannot} specify that it has a return type other than @code{int}.
@c ??? The implementation is allowed to support alternative signatures.
@cindex exit status
@cindex @code{EXIT_FAILURE}
@cindex @code{EXIT_SUCCESS}
@cindex return value of @code{main}
In general, the return value from @code{main} indicates the program's
@dfn{exit status}. A value of zero or EXIT_SUCCESS indicates success
and EXIT_FAILURE indicates an error. Otherwise, the significance of
the value returned is implementation-defined.
@c ??? We don't define it here.
Reaching the @code{@}} at the end of @code{main} without a return, or
executing a @code{return} statement with no value (that is,
@code{return;}) are both equivalent. In C89, the effect of this is
undefined, but in C99 the effect is equivalent to @code{return 0;}.
You can write your @code{main} function to have no parameters (that
is, as @code{int main (void)}, or to accept parameters from the
command line. Here is a very simple @code{main} function with no
parameters:
@example
@group
int
main (void)
@{
puts ("Hi there!");
return 0;
@}
@end group
@end example
To accept command line parameters, you need to have two parameters in the
@code{main} function, @code{int argc} followed by @code{char *argv[]}. You
can change the names of those parameters, but they must have those data
types---@code{int} and array of pointers to @code{char}. @code{argc} is the
number of command line parameters, including the name of the program itself.
@code{argv} is an array of the parameters, as character strings.
@code{argv[0]}, the first element in the array, is the name of the program
as typed at the command line@footnote{Rarely, @code{argv[0]} can be a
null pointer (in
this case @code{argc} is 0) or @code{argv[0][0]} can be the null character.
In any case, @code{argv[argc]} is a null pointer.};
any following array elements are the parameters that followed the name
of the program.
Here is an example @code{main} function that accepts command line
parameters, and prints out what those parameters are:
@example
@group
int
main (int argc, char *argv[])
@{
int counter;
for (counter = 0; counter < argc; counter++)
printf ("%s\n", argv[counter]);
return 0;
@}
@end group
@end example
@c ----------------------------------------------------------------------------
@node Recursive Functions
@section Recursive Functions
@cindex recursive functions
@cindex functions, recursive
You can write a function that is recursive---a function that calls
itself. Here is an example that computes the factorial of an integer:
@example
int
factorial (int x)
@{
if (x < 1)
return x;
else
return (x * factorial (x - 1));
@}
@end example
Be careful that you do not write a function that is infinitely recursive. In
the above example, once @code{x} is 1, the recursion stops. However, in the
following example, the recursion does not stop until the program is interrupted
or runs out of memory:
@example
@group
int
watermelon (int x)
@{
return (watermelon (x));
@}
@end group
@end example
Functions can also be indirectly recursive, of course.
@c ----------------------------------------------------------------------------
@node Static Functions
@section Static Functions
@cindex static functions
@cindex functions, static
@cindex static linkage
You can define a function to be static if you want it to be callable only
within the source file where it is defined:
@example
@group
static int
foo (int x)
@{
return x + 42;
@}
@end group
@end example
@noindent
This is useful if you are building a reusable library of functions and need to
include some subroutines that should not be callable by the end user.
Functions which are defined in this way are said to have @dfn{static
linkage}. Unfortunately the @code{static} keyword has multiple
meanings; @ref{Storage Class Specifiers}.
@c ----------------------------------------------------------------------------
@node Nested Functions
@section Nested Functions
@cindex nested functions
@cindex functions, nested
As a GNU C extension, you can define functions within other functions, a
technique known as nesting functions.
Here is an example of a tail-recursive factorial function, defined
using a nested function:
@example
@group
int
factorial (int x)
@{
int
factorial_helper (int a, int b)
@{
if (a < 1)
@{
return b;
@}
else
@{
return factorial_helper ((a - 1), (a * b));
@}
@}
return factorial_helper (x, 1);
@}
@end group
@end example
Note that nested functions must be defined along with variable
declarations at the beginning of a function, and all other statements
follow.