Declaring a function static and then non-static: standard?

I noticed a very curious behavior that, if it were standard, I would be very happy to use (what I would like to do with it is quite difficult to explain and not be relevant to the issue).

Behavior:

static void name(); void name() { /* This function is now static, even if in the declaration * there is no static keyword. Tested on GCC and VS. */ } 

Curiously, the converse generates a compile-time error:

 void name(); static void name() { /* Illegal */ } 

So this is the standard, and can I expect other compilers to behave the same? Thanks!

+6
c ++ c standards
source share
2 answers

C ++ Standard:

7.1.1 / 6: "A name declared in a namespace area without a storage class specifier is external if it has an internal relationship due to a previous declaration" [or if it is not const].

In your first case, name declared in the namespace area (in particular, in the global namespace). Therefore, the first declaration changes the relationship of the second declaration.

Reverse ban because:

7.1.1 / 7: "Communications implied by successive announcements for a given entity agrees."

So, in the second example, the first declaration has an external link (according to 7.1.1 / 6), and the second has an internal link (explicitly), and this is not consistent.

You are also asking about C, and I think this is the same. But I have a C ++ book right here, while you are just as capable of looking at a draft standard C project as I am ,-)

+12
source share

The qualifiers that you put in the function prototype (or implied) are automatically used when declaring the function.

So, in the second case, the lack of static in the prototype meant that the function was defined as NOT static, and then, when it was later declared as static, it was an error.

If you need to leave the return type in the prototype, then the default will be int , and then you will get an error again with the void return type. The same thing happens with __crtapi and __stdcall and __declspec() (in the Microsoft C compiler).

+3
source share

All Articles