[SOLVED] Function declaration inside of block in C

Issue

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.

Solution

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;
}

Answered By – Vlad from Moscow

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.