11

I noticed that prepending the class or struct keyword to a type that would otherwise need be forward declared works as if that type was forward declared:

// struct Test; forward declaration commented void* foo(struct Test* t) // C style function parameter - This works ! { return t; } 

I wasn't aware of that. I wonder if it's standard C++ or an extension and whether the struct keyword before the parameter works as a forward declaration or another mechanism kicks in.

Furthermore, after such a usage the "next" function can use the type without prepending any keywords :

void* oof(Test* t); 

Demo

3
  • 3
    Yes, an elaborated-type-specifier can be used to declare a type, even outside a "normal" forward declaration. The semantics is somewhat different, though. Commented Jul 29, 2015 at 9:27
  • 1
    sorry I misread your question then. Commented Jul 29, 2015 at 9:31
  • @NikosAthanasiou just that did Commented Jul 29, 2015 at 10:05

1 Answer 1

7

This is legal, but probably not a good idea.

From [basic.scope.pdecl]/6:

[...] — for an elaborated-type-specifier of the form
class-key identifier
if the elaborated-type-specifier is used in the decl-specifier-seq or parameter-declaration-clause of a function defined in namespace scope, the identifier is declared as a class-name in the namespace that contains the declaration [...]

For example:

namespace mine { struct T* foo(struct S *); // ^^^^^^^^^---------------- decl-specifier-seq // ^^^^^^^^^^--- parameter-declaration-clause } 

This introduces T and S as class-names and foo as a function name into namespace mine.


Note that the behavior is different in C; the struct name is only valid within the scope of the function.

6.2.1 Scopes of identifiers

4 - [...] If the declarator or type specifier that declares the identifier appears [...] within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block. If the declarator or type specifier that declares the identifier appears within the list of parameter declarations in a function prototype (not part of a function definition), the identifier has function prototype scope, which terminates at the end of the function declarator.

gcc gives an appropriate warning for this usage in C code:

a.c:3:18: warning: ‘struct Test’ declared inside parameter list void* foo(struct Test* t) ^ a.c:3:18: warning: its scope is only this definition or declaration, which is probably not what you want 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.