Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
C syntax
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Functions== ===Syntax=== A C function definition consists of a [[return type]] ({{code|void}} if no value is returned), a unique name, a list of parameters in parentheses, and various statements: <syntaxhighlight lang=C> <return-type> functionName( <parameter-list> ) { <statements> return <expression of type return-type>; } </syntaxhighlight> A function with non-{{code|void}} return type should include at least one {{code|return}} statement. The parameters are given by the {{code|<parameter-list>}}, a comma-separated list of parameter declarations, each item in the list being a data type followed by an identifier: {{code|<data-type> <variable-identifier>, <data-type> <variable-identifier>, ...}}. The return type cannot be an array type or function type. <syntaxhighlight lang=C> int f()[3]; // Error: function returning an array int (*g())[3]; // OK: function returning a pointer to an array. void h()(); // Error: function returning a function void (*k())(); // OK: function returning a function pointer </syntaxhighlight> If there are no parameters, the {{code|<parameter-list>}} may be left empty or optionally be specified with the single word {{code|void}}. It is possible to define a function as taking a variable number of parameters by providing the {{code|...}} keyword as the last parameter instead of a data type ad variable identifier. A commonly used function that does this is the standard library function {{code|printf}}, which has the declaration: <syntaxhighlight lang=C> int printf (const char*, ...); </syntaxhighlight> Manipulation of these parameters can be done by using the routines in the standard library header [[stdarg.h|{{code|<stdarg.h>}}]]. ====Function Pointers==== A pointer to a function can be declared as follows: <syntaxhighlight lang=C> <return-type> (*<function-name>)(<parameter-list>); </syntaxhighlight> The following program shows use of a [[function pointer]] for selecting between addition and subtraction: <syntaxhighlight lang=C> #include <stdio.h> int (*operation)(int x, int y); int add(int x, int y) { return x + y; } int subtract(int x, int y) { return x - y; } int main(int argc, char* args[]) { int foo = 1, bar = 1; operation = add; printf("%d + %d = %d\n", foo, bar, operation(foo, bar)); operation = subtract; printf("%d - %d = %d\n", foo, bar, operation(foo, bar)); return 0; } </syntaxhighlight> ===Global structure=== After preprocessing, at the highest level a [[C (programming language)|C]] [[computer program|program]] consists of a sequence of declarations at file scope. These may be partitioned into several separate source files, which may be compiled separately; the resulting object modules are then [[Linker (computing)|linked]] along with implementation-provided run-time support modules to produce an executable image. The declarations introduce [[Function (programming)|functions]], [[Variable (programming)|variables]] and [[Data type|types]]. C functions are akin to the subroutines of [[Fortran]] or the procedures of [[Pascal (programming language)|Pascal]]. A ''definition'' is a special type of declaration. A variable definition sets aside storage and possibly initializes it, a function definition provides its body. An implementation of C providing all of the standard library functions is called a ''hosted implementation''. Programs written for hosted implementations are required to define a special function called [[Entry point|{{code|main}}]], which is the first function called when a program begins executing. Hosted implementations start program execution by invoking the {{code|main}} function, which must be defined following one of these prototypes (using different parameter names or spelling the types differently is allowed): <syntaxhighlight lang=C> int main() {...} int main(void) {...} int main(int argc, char *argv[]) {...} int main(int argc, char **argv) {...} // char *argv[] and char **argv have the same type as function parameters </syntaxhighlight> The first two definitions are equivalent (and both are compatible with C++). It is probably up to individual preference which one is used (the current C standard contains two examples of {{code|main()}} and two of {{code|main(void)}}, but the draft C++ standard uses {{code|main()}}). The return value of {{code|main}} (which should be {{code|int}}) serves as ''termination status'' returned to the host environment. The C standard defines return values {{code|0}} and {{code|EXIT_SUCCESS}} as indicating success and {{code|EXIT_FAILURE}} as indicating failure. ({{code|EXIT_SUCCESS}} and {{code|EXIT_FAILURE}} are defined in [[stdlib.h|{{code|<stdlib.h>}}]]). Other return values have implementation-defined meanings; for example, under [[Linux]] a program killed by a [[Signal (computing)|signal]] yields a return code of the numerical value of the signal plus 128. A minimal correct C program consists of an empty {{code|main}} routine, taking no arguments and doing nothing: <syntaxhighlight lang=C> int main(void){} </syntaxhighlight> Because no <code>return</code> statement is present, <code>main</code> returns 0 on exit.<ref name="bk21st" /> (This is a special-case feature introduced in [[C99]] that applies only to <code>main</code>.) The {{code|main}} function will usually call other functions to help it perform its job. Some implementations are not hosted, usually because they are not intended to be used with an [[operating system]]. Such implementations are called ''free-standing'' in the C standard. A free-standing implementation is free to specify how it handles program startup; in particular it need not require a program to define a {{code|main}} function. Functions may be written by the programmer or provided by existing libraries. Interfaces for the latter are usually declared by including header files—with the {{code|#include}} [[preprocessing directive]]—and the library objects are linked into the final executable image. Certain library functions, such as [[printf|{{code|printf}}]], are defined by the C standard; these are referred to as the [[ISO C standard library|standard library]] functions. A function may return a value to caller (usually another C function, or the hosting environment for the function {{code|main}}). The {{code|printf}} function mentioned above returns how many characters were printed, but this value is often ignored. ===Argument passing=== In C, arguments are passed to functions [[pass by value|by value]] while other languages may pass variables [[pass by reference|by reference]]. This means that the receiving function gets copies of the values and has no direct way of altering the original variables. For a function to alter a variable passed from another function, the caller must pass its ''address'' (a ''pointer'' to it), which can then be dereferenced in the receiving function. See [[C syntax#Pointers|Pointers]] for more information. <syntaxhighlight lang=C> void incInt(int *y) { (*y)++; // Increase the value of 'x', in 'main' below, by one } int main(void) { int x = 0; incInt(&x); // pass a reference to the var 'x' return 0; } </syntaxhighlight> The function [[scanf]] works the same way: <syntaxhighlight lang=C> int x; scanf("%d", &x); </syntaxhighlight> In order to pass an editable pointer to a function (such as for the purpose of returning an allocated array to the calling code) you have to pass a pointer to ''that'' pointer: its address. <syntaxhighlight lang=C> #include <stdio.h> #include <stdlib.h> void allocate_array(int ** const a_p, const int A) { /* allocate array of A ints assigning to *a_p alters the 'a' in main() */ *a_p = malloc(sizeof(int) * A); } int main(void) { int * a; /* create a pointer to one or more ints, this will be the array */ /* pass the address of 'a' */ allocate_array(&a, 42); /* 'a' is now an array of length 42 and can be manipulated and freed here */ free(a); return 0; } </syntaxhighlight> The parameter {{code|int **a_p}} is a pointer to a pointer to an {{code|int}}, which is the address of the pointer {{code|p}} defined in the ''main'' function in this case. ====Array parameters==== Function parameters of array type may at first glance appear to be an exception to C's pass-by-value rule. The following program will print 2, not 1: <syntaxhighlight lang=C> #include <stdio.h> void setArray(int array[], int index, int value) { array[index] = value; } int main(void) { int a[1] = {1}; setArray(a, 0, 2); printf ("a[0]=%d\n", a[0]); return 0; } </syntaxhighlight> However, there is a different reason for this behavior. In fact, a function parameter declared with an array type is treated like one declared to be a pointer. That is, the preceding declaration of {{code|setArray}} is equivalent to the following: <syntaxhighlight lang=C> void setArray(int *array, int index, int value) </syntaxhighlight> At the same time, C rules for the use of arrays in expressions cause the value of {{code|a}} in the call to {{code|setArray}} to be converted to a pointer to the first element of array {{code|a}}. Thus, in fact this is still an example of pass-by-value, with the caveat that it is the address of the first element of the array being passed by value, not the contents of the array. Since C99, the programmer can specify that a function takes an array of a certain size by using the keyword {{code|static}}. In <code>void setArray(int array[static 4], int index, int value)</code> the first parameter must be a pointer to the first element of an array of length at least 4. It is also possible to add qualifiers (<code>const</code>, <code>volatile</code> and <code>restrict</code>) to the pointer type that the array is converted to by putting them between the brackets. ===Anonymous functions=== {{Excerpt|Examples of anonymous functions|C (non-standard extension)|subsections=yes}}
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)