سؤال

I'm having trouble understanding the result of using void when calling a method. Below is a main() that calls a test(). The test() has a return of void.

If I call void test() (use void) the execution seems to stop: no print from test()

If I call test() (no void) the execution works fine.

What is the logic of this? I'm thinking that the word void in the call is somehow waiting for a return from test() which never comes? But wouldn't that be after test() did its job of printing? In the call is it sending void and test() not handling it?

Note: This is from a C language for a Propeller microcontroller, perhaps the logic is different than C on a PC. Much thanks.

#include "simpletools.h";
void testerForVoid(); //forward declare

int main(void)
{
    print("Begin main");

    // option 1 - no void - works
    testerForVoid(); 

    // option 2 - with void - fails
    void testerForVoid(); 

    return 0;
}

void testerForVoid()
{
    print("\nBegin testForVoid");
}
هل كانت مفيدة؟

المحلول

void is only used in the function declaration. When you call a function with void return type, just call it without using void.

  • Use void testerForVoid(); to declare a function that returns void, as the forward declared in your case.

  • Use testerForVoid(); to call the function.

In you example, for option#2, it tends to declare the function again, which has already been forward declared. No real function all is conducted.

نصائح أخرى

void testerForVoid(); declares a function that returns void (does nothing)

testerForVoid(); calls the function

option 1 is a call to function testerForVoid() which has already been declared.

option 2 is a declaration of function testerForVoid(). This fails because it has already been declared.

Actually this is just declaration:

void testerForVoid(); 

And this is actual call.

testerForVoid(); 

You may call function like this,

void Fun()
{
    printf("Fun");
}
int main(int argc, char* argv[])
{
    (void) Fun();//like this
    return 0;
}

Just to show your function returns void.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top