Does the C standard (C99 ) require the implementation to allow function declarations to be placed within a block in order to limit their scope to that block and where is this covered in the standard? Assume the function has external linkage and is defined in a separate source file to be included when linking.
I noticed that GCC generates an error when the following program is compiled:
int main(void)
{
void myFunc(void);
myFunc();
return 0;
}
void test2(void)
{
myFunc();
}
Error (which is expected):
..\main.c: In function 'test2':
..\main.c:12:3: warning: implicit declaration of function 'myFunc' [-Wimplicit-function-declaration]
12 | myFunc();
| ^~~~~~
..\main.c:3:8: note: previous declaration of 'myFunc' was here
3 | void myFunc(void);
| ^~~~~~
..\main.c:12:3: error: incompatible implicit declaration of function 'myFunc'
12 | myFunc();
| ^~~~~~
..\main.c:3:8: note: previous implicit declaration of 'myFunc' was here
3 | void myFunc(void);
| ^~~~~~
This would be expected since myFunc()
is declared within the scope of main()
.
If the call to myFunc()
is removed from test2()
, and test2()
is defined in another source file included when linking, then the program compiles and links with no errors or warnings.
Based on this result, the answer to the question would be yes, but I am wondering if this behavior is explicitly defined in the specification and can be considered portable.
CodePudding user response:
Within the function
void test2(void)
{
myFunc();
}
the name myFunc
is undeclared.
The declaration of the function is visible only within main.
For backward compatibility the compiler considers that the function has the return type int
.
As for your question then you may declare a function within a block scope but without a storage class specifier except extern
(the C Standard, 6.7.1 Storage-class specifiers):
6 The declaration of an identifier for a function that has block scope shall have no explicit storage-class specifier other than extern.
That is you may not declare a function in a block scope for example like
int main(void)
{
static void myFunc(void);
myFunc();
return 0;
}
CodePudding user response:
Does the C standard (C99 ) require the implementation to allow function declarations to be placed within a block in order to limit their scope to that block?
Yes.
where is this covered in the standard?
Follow the grammar: function-definition -> compund-statement -> block-item-list -> block-item -> declaration-specifiers -> [ declaration-specifiers -> type-specifier void
init-declarator-list -> init-declarator -> declarator -> [ direct-declarator myFunc
(
empty identifier-list )
] ;
].
The notation used to represent the grammar is also explained: https://port70.net/~nsz/c/c99/n1256.html#6.1p1 .
In other words, a function definition has a block of code, which consist of declarations and expressions. And a function declaration is one of possible declarations, so it can be inside the block inside a function definition.