Function Parameters And Return Types In C

Posted on November 10, 2023 by Vishesh Namdev
Python C C++ Javascript Java
C Programming Language

Functions often require input data, known as parameters, and they can provide output data, known as the return type. Let's explore the details of function parameters and return types:

Function Parameters:

1. Syntax for Declaring Parameters:

Parameters are variables that a function can accept. They are declared within parentheses in the function declaration and definition.

// Function definition
return_type function_name ( parameter_type1 parameter_name1 , parameter_type2 parameter_name2 , ...) {
// Function body
}
2. Passing Values to Functions:

When you call a function, you provide values for its parameters. These values are called arguments. .

// Function definition
int add ( int a , int b ) {
return a + b ;
}

// Calling the function with arguments
int result = add ( 3 , 5 );
3. Types of Parameters:

Parameters can be of different types, such as integers, floats, characters, or custom-defined types.

// Function definition
void printMessage ( char message []) {
printf (" %s \n", message );
}

Return Types:

1. Syntax for Return Types:

The return type specifies the type of value that the function will return. It is declared before the function name.

// Function definition
return_type function_name ( parameter_type1 parameter_name1 , parameter_type2 parameter_name2 , ...) {
// Function body
}
2. Returning Values:

The return statement is used to send a value back to the calling part of the program. The type of the return value must match the declared return type.

// Function definition
int square ( int x ) {
return x * x ;
}

// Calling the function and using the returned value
int result = square ( 4 );
3. Void Return Type:

Functions with no return value use the void keyword.

// Function definition
// Function definition
void greet () {
printf ("Hello!\n");
}

Notes:

a. Matching Types:

1. The types of function parameters in the declaration and definition must match.

2. The type of the value returned by the function must match the declared return type.

b. Multiple Parameters:

1. Functions can have multiple parameters, allowing them to accept and process more data.
// Function definition
int addThreeNumbers ( int a , int b , int c ) {
return a + b + c ;
}