Home > Net >  Multiple function calling?
Multiple function calling?

Time:11-15

Hi extremely new to programming. Just want to know if for example I have a function called void blink(void). If I write a code

2 * blink();

is it the same as

blink();
blink();

?

CodePudding user response:

2 * blink();

No, this will not call blink() 2 times, this will multiply 2 with the value that blink() returns. Because blink() is void (that means blink() doesn't return anything), this will cause an error.

I have a variable 'num' and I want the function to be called as much as the num value

You should use a for loop. For example:

for(int i = 1; i <= num;   i)
/* this is the same as for(int i = 0; i < num;   i) */
{
    blink();
}

CodePudding user response:

I do not know where you took this syntax from, but it will not call the function twice. It will multiply the function return value by two.

int blink(void)
{
    return 5;
}

int main(void)
{
    int result;

    result = 2 * blink();
    printf("%d\n", result);
}

https://godbolt.org/z/4nrGj3M6W

if blink has void return type it will simple not compile.

Another way of multiple calling function using function pointer:

void blink(void)
{
    printf("BLIMK!!!\n");
}

void callMultiple(void (*func)(void), size_t ntimes)
{
    while(ntimes--) func();
}


int main(void)
{
    size_t times;

    if(scanf("%zu", &times) == 1)
    {
        callMultiple(blink, times);
    }
}

https://godbolt.org/z/jWEd9hnK9

  • Related