Reputation: 2812
What are the different ways to call a function? For example, can I call a function without ()?
Upvotes: 3
Views: 2134
Reputation: 5579
There are several pedantic ways to invoke a function without using (). Naming the function "main" (with correct parameter & return types) is one good way. You could register it as an interrupt handler. You could trick the compiler into jumping into it by smashing the stack (not portable and not recommended, works with gcc on 64-bit x86):
#include <stdio.h>
void foo()
{
printf("In foo\n");
}
void bar()
{
long long a;
long long *b = &a;
void (*fooptr)() = &foo;
b[2] = (long long)fooptr;
}
int main()
{
bar();
}
Upvotes: 1
Reputation: 84169
In C the ()
is the function invocation syntax. You cannot call a function without it.
Upvotes: 4
Reputation: 76541
You can call by name:
function_name(args);
You can call by function pointer:
void (*function_pointer)(int, char *) = ...;
(*function_pointer)(3, "moo"); // classic function pointer syntax
function_pointer(3, "moo"); // alternate syntax which obscures that it's using a function pointer
No, you cannot call a function without using ()
. You can hide the ()
by using a macro but that just hides where they are; in the end you must use ()
somewhere.
Upvotes: 5
Reputation: 3212
You can use a macro:
#define f func()
but this is not a recommended way. Your code will be very difficult to read and understand.
Upvotes: 4