Trevor
Trevor

Reputation: 49

Calling a function in C not producing a function

I am new to C and it is so far very, different. Nevertheless I am trying to call a function from the main function using scanf and a switch statement however I do not believe the function I call is functioning.

int main(void)
{
    int Example_number = 0;
    bool Continue = true;
    char ch;

    while(Continue)
    {
        printf("Which example would you like to run?\n");
        scanf("%d",&Example_number);

        switch(Example_number)
        {
        default: printf("No such program exists.\n");
                 break;
        case 1:  void Various_test();
                 break;
        }

        printf("Would you like to test another?(Y/N)\n");
        scanf("\n%c",&ch);
        if(ch == 'Y' || ch == 'y')
        {
            NULL;
        }
        else
        {
            Continue = false;
        }
    }
}

void Various_test(void)
{
    int k = 2;
    printf("\n%d",k);
}

I'm hoping for the program to print a 2 if a 1 is the input, however the while loop just repeats.

Thank you for your consideration of this question.

Upvotes: 0

Views: 89

Answers (2)

Nocturno
Nocturno

Reputation: 10027

You can do one of two things:

Add the function declaration at the beginning of main, like this:

int main(void)
{
    void Various_test(void);
    ...

Or, move the function definition of Various_test to just before main, like this:

void Various_test(void)
{
    int k = 2;
    printf("\n%d",k);
}

int main(void)
{
    int Example_number = 0;
    ...

Either way you choose will work the same. As you have it right now, the compiler doesn't know about the Various_test function. Either way tells the compiler there is a function named Various_test, and this is what it looks like.

One more thing, you're calling Various_test wrong in your switch statement:

case 1:  void Various_test();

Should be:

case 1:  Various_test();

Upvotes: 1

Ben Jackson
Ben Jackson

Reputation: 93890

void Various_test() is a forward declaraction of the function. To call it you really just want Various_test(). You may actually need the forward declaration (depending on your compile options). In that case put void Various_test(); above main.

Upvotes: 4

Related Questions