Functions & Methods
A function parameter is a variable used in a function. Function parameters work almost identically to variables defined inside the function, but with one difference: they are always initialized with a value provided by the caller of the function.
An argument is a value that is passed from the caller to the function when a function call is made.
Source: https://www.learncpp.com/cpp-tutorial/introduction-to-function-parameters-and-arguments/
- C
- C++
- C#
- Java
- Rust
- Go
- Javascript
- Typescript
- Python
// ------------------------------------
// Definition
// ------------------------------------
[return_type] functionName( [parameters] )
{
// ...
}
// I C, functions must be declared before its use.
// It is also possible to use a declaration statement called a
// "Function prototype"
[return_type] functionName( [parameters] ); // ; (Semicolon) here and without Body
// And later, the proper declaration
// ------------------------------------
// Declaration Example
// ------------------------------------
void myFunction(float x)
{
// ...
}
float myFunction()
{
// ...
}
myStruct myFunction( float x, float y)
{
// ...
}
myClass myFunction( float x, float y)
{
// ...
}
// ------------------------------------
// Named Parameters (Keyword Arguments)
// ------------------------------------
// No Native Support. There are Workarounds
// ------------------------------------
// Optional Parameters
// ------------------------------------
// No Native Support. There are Workarounds
// ------------------------------------
// Default Argument for Parameters
// ------------------------------------
// No Native Support. There are Workarounds
// ------------------------------------
// Variable Number of Arguments to a Function Parameters
// ------------------------------------
#include <stdarg.h> // For va_list, va_start(), va_args()
// "count" - how many variables
// "..." - the variables
int add_all_int(int count, ...) // "..." (ellipsis) can only occur at the end
{
va_list arguments;
va_start(arguments, count); // Dynamic allocate "arguments" with "count" size
int result = 0;
for(int i = 0; i < count; i++)
{
// var_args(va_list_variable, count_type)
result += va_arg(arguments, int);
}
va_end(arguments); // Free the memory
return result;
}
// add 2 ints: (2+4)
add_all_int(2 ,2,4);
// add 3 ints: (2+4+7)
add_all_int(3 ,2,4,7);
// ------------------------------------
// Generic/Template
// ------------------------------------
// No Native Support.
// Common options are macros, void pointers, or separate functions per type.
#define max(a, b) ((a) > (b) ? (a) : (b))
int result = max(10, 20);
// ------------------------------------
// Static
// ------------------------------------
// Check Static Section
// ------------------------------------
// Definition
// ------------------------------------
[return type] functionName( [parameters] )
{
// ...
}
// I C++, functions must be declared before its use.
// It is also possible to use a declaration statement called a
// "Function prototype"
[return type] functionName( [parameters] ); // ; (Semicolon) here and without Body
// And later, the proper declaration
// ------------------------------------
// Declaration Example
// ------------------------------------
void myFunction(float x)
{
// ...
}
float myFunction()
{
// ...
}
myStruct myFunction( float x, float y)
{
// ...
}
myClass myFunction( float x, float y)
{
// ...
}
// ------------------------------------
// Named Parameters (Keyword Arguments)
// ------------------------------------
// No Native Support Yet.
// ------------------------------------
// Optional Parameters
// ------------------------------------
// All Parameters with default values are optional
// All Optional Parameters must be at the end.
// ------------------------------------
// Default Argument for Parameters
// ------------------------------------
void myFunction(float x, float y=10) // 10 is the default argument. Y is now an Optional Parameter
{
// ...
}
myFunction(20);
myFunction(20, 30);
// ------------------------------------
// Variable Number of Arguments to a Function Parameters
// ------------------------------------
// Option 1 - Fold Expressions (Since C++ 17)
template<typename ...Args>
auto add_all(Args ...args)
{
return (args + ...);
}
// add 2 ints: (2+4)
add_all({2,4});
// add 3 ints: (2+4+7)
add_all({2,4,7});
// Option 2 - Variadic Templates (Since C++ 11)
#include <initializer_list>
template <typename T>
T add_all( std::initializer_list<T> list )
{
T result = 0.0;
for( auto element : list )
{
result += element;
}
return result;
}
// add 2 ints: (2+4)
add_all({2,4});
// add 3 ints: (2+4+7)
add_all({2.1,4.2,7.3});
// Old Way
#include <cstdarg> // For va_list, va_start(), va_args()
// "count" - how many variables
// "..." - the variables
int add_all_int(const int count, ...) // "..." (ellipsis) can only occur at the end
{
va_list arguments;
va_start(arguments, count); // Dynamic allocate "arguments" with "count" size
int result = 0;
for(int i = 0; i < count; i++)
{
// var_args(va_list_variable, count_type)
result += va_arg(arguments, int);
}
va_end(arguments); // Free the memory
return result;
}
// add 2 ints: (2+4)
add_all_int(2 ,2,4);
// add 3 ints: (2+4+7)
add_all_int(3 ,2,4,7);
// ------------------------------------
// Generic/Template
// ------------------------------------
template <typename T>
T identity(T value)
{
return value;
}
template <typename T>
T max(T first, T second)
{
return first > second ? first : second;
}
auto result = max(10, 20);
// ------------------------------------
// Static
// ------------------------------------
// Check Static Section
// ------------------------------------
// Definition
// ------------------------------------
[access_modifier] [return_type] FunctionName([parameters])
{
// ...
}
// ------------------------------------
// Declaration Example
// ------------------------------------
void MyFunction(float x)
{
// ...
}
float MyFunction()
{
return 10.5f;
}
User MyFunction(int id)
{
return new User();
}
// ------------------------------------
// Named Parameters (Keyword Arguments)
// ------------------------------------
void PrintUser(string name, int age)
{
// ...
}
PrintUser(name: "Ada", age: 36);
PrintUser(age: 36, name: "Ada");
// ------------------------------------
// Optional Parameters
// ------------------------------------
// Optional parameters must appear after required parameters.
void PrintUser(string name, int age = 0)
{
// ...
}
PrintUser("Ada");
PrintUser("Ada", 36);
// ------------------------------------
// Default Argument for Parameters
// ------------------------------------
void Connect(string host, int port = 443, bool useSsl = true)
{
// ...
}
// ------------------------------------
// Variable Number of Arguments to a Function Parameters
// ------------------------------------
int AddAll(params int[] numbers)
{
int result = 0;
foreach (int number in numbers)
{
result += number;
}
return result;
}
AddAll(1, 2, 3);
// ------------------------------------
// Generic/Template
// ------------------------------------
T Identity<T>(T value)
{
return value;
}
T Max<T>(T first, T second) where T : IComparable<T>
{
return first.CompareTo(second) >= 0 ? first : second;
}
// ------------------------------------
// Static
// ------------------------------------
// Check Static Section
// ------------------------------------
// Definition
// ------------------------------------
[access_modifier] [return_type] functionName([parameters]) {
// ...
}
// ------------------------------------
// Declaration Example
// ------------------------------------
void myFunction(float x) {
// ...
}
float myFunction() {
return 10.5f;
}
User myFunction(int id) {
return new User();
}
// ------------------------------------
// Named Parameters (Keyword Arguments)
// ------------------------------------
// No Native Support.
// Use an object, builder, or clear method names when argument meaning is not obvious.
createUser(new CreateUserRequest("Ada", 36));
// ------------------------------------
// Optional Parameters
// ------------------------------------
// No Native Support.
// Use method overloading.
void connect(String host) {
connect(host, 443);
}
void connect(String host, int port) {
// ...
}
// ------------------------------------
// Default Argument for Parameters
// ------------------------------------
// No Native Support.
// Use method overloading or assign defaults inside the method.
// ------------------------------------
// Variable Number of Arguments to a Function Parameters
// ------------------------------------
int addAll(int... numbers) {
int result = 0;
for (int number : numbers) {
result += number;
}
return result;
}
addAll(1, 2, 3);
// ------------------------------------
// Generic/Template
// ------------------------------------
public static <T> T identity(T value) {
return value;
}
public static <T extends Comparable<T>> T max(T first, T second) {
return first.compareTo(second) >= 0 ? first : second;
}
// ------------------------------------
// Static
// ------------------------------------
// Check Static Section
// ------------------------------------
// Definition
// ------------------------------------
fn function_name([parameters]) -> return_type {
// ...
}
// ------------------------------------
// Declaration Example
// ------------------------------------
fn my_function(x: f32) {
// ...
}
fn get_number() -> f32 {
10.5
}
fn add(first: i32, second: i32) -> i32 {
first + second
}
// ------------------------------------
// Named Parameters (Keyword Arguments)
// ------------------------------------
// No Native Support.
// Use structs when argument names matter.
struct CreateUserOptions {
name: String,
age: u8,
}
fn create_user(options: CreateUserOptions) {
// ...
}
// ------------------------------------
// Optional Parameters
// ------------------------------------
// No Native Support.
// Use Option<T> or separate functions.
fn print_user(name: &str, age: Option<u8>) {
// ...
}
// ------------------------------------
// Default Argument for Parameters
// ------------------------------------
// No Native Support.
// Use Option<T>, builder-style structs, or wrapper functions.
// ------------------------------------
// Variable Number of Arguments to a Function Parameters
// ------------------------------------
// No Native Support for variadic Rust functions.
// Pass a slice or vector.
fn add_all(numbers: &[i32]) -> i32 {
numbers.iter().sum()
}
add_all(&[1, 2, 3]);
// ------------------------------------
// Generic/Template
// ------------------------------------
fn identity<T>(value: T) -> T {
value
}
fn max<T: Ord>(first: T, second: T) -> T {
if first >= second {
first
} else {
second
}
}
// ------------------------------------
// Static
// ------------------------------------
// Check Static Section
// ------------------------------------
// Definition
// ------------------------------------
func functionName([parameters]) [returnType] {
// ...
}
// ------------------------------------
// Declaration Example
// ------------------------------------
func myFunction(x float32) {
// ...
}
func getNumber() float32 {
return 10.5
}
func add(first int, second int) int {
return first + second
}
func swap(first string, second string) (string, string) {
return second, first
}
// ------------------------------------
// Named Parameters (Keyword Arguments)
// ------------------------------------
// No Native Support.
// Use structs when argument names matter.
type CreateUserOptions struct {
Name string
Age int
}
func CreateUser(options CreateUserOptions) {
// ...
}
// ------------------------------------
// Optional Parameters
// ------------------------------------
// No Native Support.
// Use zero values, structs, or separate functions.
// ------------------------------------
// Default Argument for Parameters
// ------------------------------------
// No Native Support.
// Assign defaults inside the function when needed.
// ------------------------------------
// Variable Number of Arguments to a Function Parameters
// ------------------------------------
func addAll(numbers ...int) int {
result := 0
for _, number := range numbers {
result += number
}
return result
}
addAll(1, 2, 3)
// ------------------------------------
// Generic/Template
// ------------------------------------
// Since Go 1.18
func Identity[T any](value T) T {
return value
}
func Contains[T comparable](values []T, target T) bool {
for _, value := range values {
if value == target {
return true
}
}
return false
}
// ------------------------------------
// Static
// ------------------------------------
// Check Static Section
// ------------------------------------
// Definition
// ------------------------------------
function functionName( [parameters] ) {
// ...
}
// Self Invoking Function
(function functionName( [parameters] ) {
// ...
})();
// For "Arrow Functions" Check Lambda Section
// ------------------------------------
// Declaration Example
// ------------------------------------
function functionName(x, y) {
// ...
}
// Self Invoking Function
(function main() {
// Code Here
})();
// ------------------------------------
// Named Parameters (Keyword Arguments)
// ------------------------------------
// Not available natively as some might expect BUT
// Javascript can use Object Destructuring to simulate this
function functionName( { parameter1, parameter2, parameter3 } ) {
// ...
}
// Using Keyword Arguments, order doesnt matter
// The passed keyword name should match with the actual keyword name.
functionName( { parameter3: '!', parameter1: 'Hello', parameter2: 'World' } );
// Since we're using a javascript object, you can also do like this:
const myParameters = { parameter3: '!', parameter1: 'Hello', parameter2: 'World' };
functionName(myParameters);
// ------------------------------------
// Optional Parameters
// ------------------------------------
// All Parameters with default values are optional
// All Optional Parameters must be at the end.
// ------------------------------------
// Default Argument for Parameters
// ------------------------------------
// Option 1
function functionName(parameter1, parameter2, parameter3='Default String') {
// ...
}
functionName('Hello', 'World');
functionName('Hello', 'World', '!');
// Option 2 - Object Destructuring
function functionName( { parameter1='Hello', parameter2='World', parameter3='Default String' } = {}) {
// ...
}
functionName({ parameter1: 'Hello', parameter2: 'World'});
functionName({ parameter1: 'Hello', parameter2: 'World', parameter3: '!'});
// ------------------------------------
// Variable Number of Arguments to a Function Parameters
// ------------------------------------
// Option 1 - rest parameters syntax (Also Known as Spread Operator)
function addAll(...args) {
let result = 0;
for (element of args) {
result += element
}
return result
}
console.log(addAll(1, 2, 3))
// Option 2 - Arguments Object
// No need to add a Parameter
function addAll() {
let result = 0;
// Special keyword "arguments"
for (element of arguments) {
result += element
}
return result
}
// The arguments object is not an Array. It is similar, but
// lacks all Array properties except length.
console.log(addAll(1,2,3));
// ------------------------------------
// Generic/Template
// ------------------------------------
// No Native Support.
// Javascript functions are dynamically typed.
function identity(value) {
return value;
}
// ------------------------------------
// Static
// ------------------------------------
// Check Static Section
More Info:
- https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1
- https://zendev.com/2018/10/01/javascript-arrow-functions-how-why-when.html
- https://stackoverflow.com/questions/31362292/how-to-use-arrow-functions-public-class-fields-as-class-methods
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
// ------------------------------------
// Definition
// ------------------------------------
function functionName([parameters]): returnType {
// ...
}
// ------------------------------------
// Declaration Example
// ------------------------------------
function myFunction(x: number): void {
// ...
}
function getNumber(): number {
return 10.5;
}
function add(first: number, second: number): number {
return first + second;
}
// ------------------------------------
// Named Parameters (Keyword Arguments)
// ------------------------------------
// No Native Support.
// Use object parameters.
function printUser({ name, age }: { name: string; age: number }): void {
// ...
}
printUser({ name: "Ada", age: 36 });
// ------------------------------------
// Optional Parameters
// ------------------------------------
function printUser(name: string, age?: number): void {
// ...
}
// ------------------------------------
// Default Argument for Parameters
// ------------------------------------
function connect(host: string, port: number = 443): void {
// ...
}
// ------------------------------------
// Variable Number of Arguments to a Function Parameters
// ------------------------------------
function addAll(...numbers: number[]): number {
return numbers.reduce((result, number) => result + number, 0);
}
addAll(1, 2, 3);
// ------------------------------------
// Generic/Template
// ------------------------------------
function identity<T>(value: T): T {
return value;
}
function first<T>(values: T[]): T | undefined {
return values[0];
}
// ------------------------------------
// Static
// ------------------------------------
// Check Static Section
# ------------------------------------
# Definition
# ------------------------------------
# There are no "{ }", you need to use ":" and indentation
# You can have either spaces or tabs but not both mixed
# In Python if you declare a variable in a block scope (if statement, for statement, ...)
# the variable is hoisted to the outer function scope.
def function_name ( [parameters] ):
# ...
def function_name ( [parameters] ) -> [return_type]: # Optional Type Annotations (PEP 484 / Python 3.6+)
# ...
# Python Methods might have the first Parameter as
# "self" or "cls".
# "self" points to an instance (object) of the class when the method is called.
# Through the self parameter, instance methods can freely access attributes and
# other methods on the same object.
def method_name(self):
# ...
# "cls" points to the class (not the object instance) when the method is called.
@classmethod
def method_name(cls):
# ...
# ------------------------------------
# Declaration Example
# ------------------------------------
def my_function ():
# ...
def my_function ( x: str ) -> str: # Type Annotations (PEP 484 / Python 3.6+)
# ...
def my_function ( x: int, y: int ) -> None:
# ...
# ------------------------------------
# Named Parameters (Keyword Arguments)
# ------------------------------------
def my_function (parameter1, parameter2, parameter3):
# ...
# Using Keyword Arguments, order doesnt matter
# The passed keyword name should match with the actual keyword name.
my_function(parameter3 = '!', parameter1 = 'Hello', parameter2 = 'World')
# ------------------------------------
# Optional Parameters
# ------------------------------------
# All Parameters with default values are optional
# All Optional Parameters must be at the end.
# ------------------------------------
# Default Argument for Parameters
# ------------------------------------
def my_function (parameter1, parameter2, parameter3='Default String'):
# ...
my_function('Hello', 'World', '!')
my_function('Hello', 'World')
my_function(parameter3 = '!', parameter1 = 'Hello', parameter2 = 'World')
my_function(parameter1 = 'Hello', parameter2 = 'World')
# ------------------------------------
# Variable Number of Arguments to a Function Parameters
# ------------------------------------
# *args allows you to pass a varying number of positional arguments.
def add_all(*args): # Unpacking Operator (*)
result = 0
for element in args:
result += element
return result
print(add_all(1, 2, 3))
# **kwargs works just like *args, but instead of accepting positional arguments
# it accepts keyword (or named) arguments.
# Example 1
def add_all(**kwargs):
result = 0
for key, value in kwargs.items():
print ("%s: %s" %(key, value))
result += value
return result
print(add_all(energy_bill = 1, car_bill = 2, school_bill = 3))
# Example 2
def concatenate(**kwargs):
result = ''
for element in kwargs.values():
result += element
return result
print(concatenate(first = 'Hello ', second = 'World', third = '!'))
# Everything Together
def my_function(parameter1, parameter2, *args, **kwargs):
# ...
# ------------------------------------
# Generic/Template
# ------------------------------------
from typing import TypeVar
T = TypeVar("T")
def identity(value: T) -> T:
return value
# Since Python 3.12, type parameters can also be declared inline.
def first[T](values: list[T]) -> T | None:
return values[0] if values else None
# ------------------------------------
# Static
# ------------------------------------
# Check Static Section
More Info: