Functions

Defining and Calling Functions

In Objective-C, functions are defined outside of any class or method and can be called from anywhere in the program where they are visible. Functions can accept parameters and return values.

Defining Functions

A function definition includes the return type, function name, and parameters (if any).

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

To call a function, simply use its name followed by arguments in parentheses.

// Function call
int result = add(5, 3);  // result is 8
NSLog(@"The result is %d", result);

Function Parameters and Return Values

Functions can accept parameters and return values of various data types.

Function with Parameters

You can define a function with parameters to pass values to it.

// Function with parameters
void printGreeting(NSString *name) {
    NSLog(@"Hello, %@", name);
}

// Calling the function with an argument
printGreeting(@"Alice");
Function with Return Value

A function can return a value using the return statement.

// Function with a return value
double multiply(double x, double y) {
    return x * y;
}

// Calling the function and storing the return value
double product = multiply(4.5, 2.3);
NSLog(@"The product is %f", product);
Function with No Parameters and No Return Value

You can also define a function with no parameters and no return value.

// Function with no parameters and no return value
void sayHello() {
    NSLog(@"Hello, world!");
}

// Calling the function
sayHello();

Function Pointers

Function pointers are used to store the address of a function, allowing you to call a function indirectly.

Declaring a Function Pointer

To declare a function pointer, specify the return type, followed by (*pointerName), and the parameter list.

// Declare a function pointer
int (*operation)(int, int);
Assigning a Function to a Function Pointer

Assign a function to a function pointer by specifying the function’s name without parentheses.

// Use the function pointer to call the function
int sum = operation(10, 5);  // Calls the 'add' function
NSLog(@"The sum is %d", sum);

Example: Using Function Pointers

Here’s a complete example demonstrating the use of function pointers:

#include <Foundation/Foundation.h>

// Define a function
int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Declare a function pointer
        int (*operation)(int, int);

        // Assign functions to the function pointer and call them
        operation = add;
        NSLog(@"Add: %d", operation(10, 5));  // Outputs 15

        operation = subtract;
        NSLog(@"Subtract: %d", operation(10, 5));  // Outputs 5
    }
    return 0;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *