Return Type

The return type of a function establishes the size and type of the value returned by the function. It corresponds to the type-specifier in the Syntax section:

Syntax

function-definition:
declaration-specifiersopt attribute-seqopt declarator declaration-listopt compound-statement

/* attribute-seq is Microsoft-specific */

declaration-specifiers:
storage-class-specifier declaration-specifiersopt
type-specifier declaration-specifiersopt
type-qualifier declaration-specifiersopt

type-specifier:
void
char
short
int
__int8 /* Microsoft-specific */
__int16 /* Microsoft-specific */
__int32 /* Microsoft-specific */
__int64 /* Microsoft-specific */
long
long long
float
double
long double
signed
unsigned
struct-or-union-specifier
enum-specifier
typedef-name

The type-specifier can specify any fundamental, structure, or union type.

The return type given in the function definition must match the return type in declarations of the function elsewhere in the program. A function returns a value when a return statement containing an expression is executed. The expression is evaluated, converted to the return value type if necessary, and returned to the point at which the function was called. If a function is declared with return type void, a return statement containing an expression generates a warning, and the expression isn't evaluated.

The following examples illustrate function return values.

typedef struct
{
    char name[20];
    int id;
    long class;
} STUDENT;

/* Return type is STUDENT: */

STUDENT sortstu( STUDENT a, STUDENT b )
{
    return ( (a.id < b.id) ? a : b );
}

This example defines the STUDENT type with a typedef declaration and defines the function sortstu to have STUDENT return type. The function selects and returns one of its two structure arguments. In subsequent calls to the function, the compiler checks to make sure the argument types are STUDENT.

Note

Efficiency would be enhanced by passing pointers to the structure, rather than the entire structure.

char *smallstr( char s1[], char s2[] )
{
    int i;

    i = 0;
    while ( s1[i] != '\0' && s2[i] != '\0' )
        i++;
    if ( s1[i] == '\0' )
        return ( s1 );
    else
        return ( s2 );
}

This example defines a function returning a pointer to an array of characters. The function takes two character arrays (strings) as arguments and returns a pointer to the shorter of the two strings. A pointer to an array points to the first of the array elements and has its type; thus, the return type of the function is a pointer to type char.

You need not declare functions with int return type before you call them, although prototypes are recommended so that correct type checking for arguments and return values is enabled.

See also

C Function Definitions