Function Prototype Scope

suggest change
#include <stdio.h>

/* The parameter name, apple, has function prototype scope.  These names
   are not significant outside the prototype itself.  This is demonstrated
   below. */

int test_function(int apple);

int main(void)
{
    int orange = 5;

    orange = test_function(orange);
    printf("%d\r\n", orange); //orange = 6

    return 0;
}

int test_function(int fruit)
{
    fruit += 1;
    return fruit;
}

Note that you get puzzling error messages if you introduce a type name in a prototype:

int function(struct whatever *arg);

struct whatever
{
    int a;
    // ...
};

int function(struct whatever *arg)
{
    return arg->a;
}

With GCC 6.3.0, this code (source file dc11.c) produces:

$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -c dc11.c
dc11.c:1:25: error: struct whatever declared inside parameter list will not be visible outside of this definition or declaration [-Werror]
     int function(struct whatever *arg);
                         ^~~~~~~~
dc11.c:9:9: error: conflicting types for function
     int function(struct whatever *arg)
         ^~~~~~~~
dc11.c:1:9: note: previous declaration of function was here
     int function(struct whatever *arg);
         ^~~~~~~~
cc1: all warnings being treated as errors
$

Place the structure definition before the function declaration, or add struct whatever; as a line before the function declaration, and there is no problem. You should not introduce new type names in a function prototype because there’s no way to use that type, and hence no way to define or use that function.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents