Functions

Function Declaration in C

A function (method) is a block of code that can be called from another location in the program or class. It is used to reduce the repetition of multiple lines of code.


Syntax
returnType functionName(parameterTypes); //function prototype

//main code

returnType functionName (functionParameters) { //function implementation
    //statements that execute when called
    return value;
}

Notes

In any version ANSI C and above, a function prototype should be declared. This ensures the correct number and type of input parameters for the function in main.

functionName is defined by the programmer, returnType is the data type returned from calling the function (void if no return). functionParameters are the inputs needed for the function to execute. Parameters are defined as: (dataType parameterName), which is the data type of the input parameter and the name of the parameter as seen within the function. There can be multiple parameters seperated by a comma.


Example
int findMaximum(int, int); //prototype

void main(){
    int maxNumber = findMaximum(5, 7); //calling a function
}

int findMaximum(int number1, int number2) { //implementation
    int maximum = number2; 
    if (number1 > number2) maximum = number1; 
    return maximum; 
}

See Also
Documentation

Function Declarations

Add to Slack

< Do-While Loop   |   Ternary Operator >

© 2019 SyntaxDB. All Rights Reserved.