I was wondering whether there is anything wrong with passing a pointer to putchar, or any other standard function which can be implemented as a macro, to a function accepting a function pointer. Below is an example of what I'm doing.
#include <stdio.h>
static int print(const char *s, int (*printc)(int))
{
int c;
while (*s != '\0') {
if ((c = printc(*s++)) < 0)
return c;
}
return printc('\n');
}
int main(void)
{
print("Hello, world", putchar);
return 0;
}
I don't have any problems compiling this with GCC and Clang under GNU/Linux, as well as GCC under OpenBSD. I'm wondering whether it will have the same behaviour under every other standard compliant implementation, since putchar can be implemented as a macro. I've searched through the standard, particularly the sections on function pointers and putchar, and haven't been able to find anything that specifies whether this is legal or not.
Thanks.
Passing Pointers to Functions in C++ C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.
When we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value. So any change made by the function using the pointer is permanently made at the address of passed variable. This technique is known as call by reference in C.
Example 2: Passing Pointers to Functions Here, the value stored at p , *p , is 10 initially. We then passed the pointer p to the addOne() function. The ptr pointer gets this address in the addOne() function. Inside the function, we increased the value stored at ptr by 1 using (*ptr)++; .
There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.
Following on from my comments-based discussion with @pmg, I found the relevant section of the standard (C99, 7.1.4 p.1):
... it is permitted to take the address of a library function even if it is also defined as a macro.161)
161) This means that an implementation shall provide an actual function for each library function, even if it also provides a macro for that function.
It is legal, because it refers to the library function, not the macro. When it is defined as a macro, that macro takes an argument, and therefore putchar with no parenthesis following does not refer to it. This is an instance of using a macro to inline functions, and should not be taken as good practice now that inlining is supported by compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With