Function(2)

박영재·2024년 10월 2일

Inline Function

  • Function call → stack management → consumption of CPU and memory resources
  • To reduce this overhead, a compiler inserts a callee function into caller function

Source code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int add(int a, int b) 
{
	return a + b;
}
int main()
{
	int input;
	scanf_s("%d", &input);

	int result = add(3, input);
	printf("%d\n", result);

	return 0;
}

Disassemble

add is removed and implanted inline main after code has been compiled

Function Pointer

Just as an array name is a pointer to its first element,

  • a function name is const variable that points to an address of the first instruction of the function [ ( ): Function Call Operator ]
  • a function pointer is a variable that contains a function name (i.e, a function pointer is a temporary alias of a function name)

How to use

  • same signature
  • (*)
  • ex)
    int add (int, int);
    
    int (*operation) (int, int);
    
    operation= add;
    
    int result = operation(3, 4);
    // other code

related code to a function pointer may not be optimized

Callback

  • Caller makes callee run a function that belongs to caller

  • Caller passes the function via a parameter

  • ex) qsort

    void qsort (
    	void* base, size_t nel, size_t width, 
    	int (*compare)(const void *, const void *)
    );
    // callback: qsort calls *compare*
  • Useful for Multi-threaded or modular programming

    Callback is related strongly to ‘asynchronous’

    • Another thread
    • Operating System

Lookup table

An array of function pointers

Higher performance than switch-case or if-else

  • No comparison
  • Prevention of branch Hazard on CPU
#include <stdio.h>

int add(int, int);
int sub(int, int);
int multiply(int, int);
int divide(int, int);

int main() {
    int (*operations[5]) (int, int);
    operations[0] = add;
    operations[1] = sub;
    operations[2] = multiply;
    operations[3] = divide;

    int op_num;
    scanf_s("%d", &op_num);

    if (op_num < 0 || op_num > 3) {
        return 1;
    }
    int result = operations[op_num](4, 5);
    printf("%d\n", result);

    return 0;
}
profile
People live above layers of abstraction beneath which engineers reside

0개의 댓글