Strange construct C found in scientific work

The code indicates:

void (* log_msg)(char *msg)
    =printf;

void change_and_log(int *buffer, int offset, int value){
    buffer[offset] = value;
    log_msg("changed");
}

I am most interested in the first part:

First, what does a signature mean void (* log_msg)(char *msg)? Does this code just map the function log_msgto printf? In this case, why the name of the function (* log_msg), and not just log_msg?

+3
source share
4 answers

This is a function pointer .

The type of the function pointer R (*)(Args...), where Rthey Args...are replaced by the type of the return value and arguments, if any. It reads as "a pointer to a function that takes arguments Args...and returns R."

Your code will be easier to read:

// print_function is a type that is a function pointer
typedef void (*print_function)(char *msg); 

// log_msg is a variable of the type print_function: it points to a function
print_function log_msg = printf; // point to printf

.

+2

void (* log_msg)(char *msg) .

typedef void (*LoggerFunctionPointer)(char* msg);

LoggerFunctionPointer log_msg = printf;

, log_msg printf, , log_msg , , printf.

, log_msg . , ,

void no_log_msg(char* msg) {}
...
if (enable_debug) {
  log_msg = printf;
} else {
  log_msg = no_log_msg;
}

, , .


(BTW, , printf int printf(const char*, ...). , log_msg

int (*log_msg)(const char*, ...) = printf;

)

+6

(, *), log_msg, printf - log_msg printf.

+2

log_msgis a function pointer , in particular a "pointer to a function that receives char *and returns void", in which case it is simply used as an alias for printf(but can point to any function with the same arguments and return type).

The syntax for function pointers in C can be quite confusing at first.

+2
source

Source: https://habr.com/ru/post/1758496/


All Articles