Home > Enterprise >  Is the C syntax: T foo<U>; valid?
Is the C syntax: T foo<U>; valid?

Time:03-03

The following code compiles and run with Clang (tested on 13, 14, and current git head), but not with GCC.

struct foo {
  int field<0, 1, int, 3>;
};

But I do not understand what it is declaring: what is this field ?

int field<0, 1, int, 3>;

I can put whatever I want in the field<> template (if it is even a template?), e.g. field<0, 1, int, 3> compiles and run. But I cannot access it afterwards.

CodePudding user response:

Assuming field isn't a template that has been declared, the program is ill-formed.

But I do not understand what it is declaring: what is this field ?

Clang AST says:

`-CXXRecordDecl 0xdb6f20 <test.cpp:1:1, line:3:1> line:1:8 struct foo definition
  `-FieldDecl 0xdb7168 <line:2:3> col:7 'int'

Clang AST for a program with int field;:

`-CXXRecordDecl 0x168af90 <test2.cpp:1:1, line:3:1> line:1:8 struct foo definition
  `-FieldDecl 0x168b150 <line:2:3, col:7> col:7 field 'int'

So, it looks like Clang thinks that an int field is being declared, but the name of the field is empty. This seems to be corroborated by being able to initialise this "unnamed" field:

foo f{0}; // compiles in Clang

The first Clang version to have this bug seems to be 9: https://gcc.godbolt.org/z/d386oz8v8

CodePudding user response:

Without a declaration of field, this isn’t even valid syntax: the < can’t begin a template argument list, and expressions aren’t allowed there in a member-declaration. (With a suitable declaration, it could be an invalid declaration with two types and no variables.) Definitely diagnosable, and definitely a Clang bug.

CodePudding user response:

Without any sort of valid definition of field member of foo, this isn't a valid C syntax.

The following code compiles and run with Clang

I tried to compile the below program:

#include <iostream>

struct foo {
  int field<0, 1, int, 3>;
};

int main(void){
    foo x;
    std::cout << x.field << std::endl;
}

With clang v13.0.1 compiler on arch linux

clang   -std=c  20 main.cc -o main

It produces some errors:

main.cc:9:20: error: no member named 'field' in 'foo'
std::cout << x.field << std::endl;
             ~ ^
1 error generated.

The above errors clearly indicates that field is not a template.

Then, I tried to compile it with gcc v11.2.0, it gave syntax error

main.cc:4:7: error: expected ‘;’ at end of member declaration
    4 |   int field<0, 1, int, 3>;
      |       ^~~~~
      |            ;
main.cc:4:12: error: expected unqualified-id before ‘<’ token
    4 |   int field<0, 1, int, 3>;

It's some kind of bug in clang v9.0 which does that.

  •  Tags:  
  • c
  • Related