Cannot declare a void function before the main() in C

4261 views c
1

I'm a beginner in C language and in my previous question I have asked about proper function declaration order in C. I was told that in standard C, it is necessary to declare functions before calling them.

But for the following example code I cannot declare the the function times2p before the main(). I tried to declare it as: void times2p(int in_data); right before the main(), but I get errors. Here below is the example code:

#include <stdio.h>
#include <stdlib.h>

 void times2p(int *in_data);
 void times2(int in_data);


int main()
{

    int y = 5;
    int s = times2(y);
    printf("%d\n", y);
    printf("%d\n", s);

    printf("-------------\n");

    int yp = 5;
    times2p(&yp);
    printf("%d\n", yp);

    return 0;
}
//Multiplies the input argument by two
void times2(int in_data){
    in_data = in_data*2;
}

void times2p(int *in_data){
    *in_data = *in_data*2;
}

How and where should the times2p function be declared in this case? If I don't declare the code still compiles without error but I was told that I have to declare the functions in C in my previous question.

answered question

Is that because you should have declared it as void times2p(int *in_data); to match the function definition? A missing *.

And what were those errors?

You edited that the code "compiles without error" if you don't declare the function. There should be warnings though?

Sorry I edited my code sorry I wasn't expecting this quick comments. Now this is my code where I get error only if I do declare the functions before main.

1 Answer

9

This:

#include <stdio.h>
#include <stdlib.h>

//How should the function times2p be declared here?
void times2p(int *in_data);

int main()
{
    int y = 5;
    times2p(&y);
    printf("%d\n", y);

    return 0;
}

//Multiplies the input argument by two
void times2p(int *in_data){
    *in_data = *in_data*2;
}

Or even this:

#include <stdio.h>
#include <stdlib.h>

//Multiplies the input argument by two
void times2p(int *in_data){
    *in_data = *in_data*2;
}

int main()
{
    int y = 5;
    times2p(&y);
    printf("%d\n", y);

    return 0;
}

posted this

Have an answer?

JD

Please login first before posting an answer.