Excess elements in scalar initializer code compiles with gcc but not g++

10,722

According to the C 2011 Standard

The initializer for a scalar shall be a single expression, optionally enclosed in braces

The verb shall means that the compiler shall issue a diagnostic message,:)

So it is a feature or a bug of the compiler.:)

According to the C Standard

1 A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint, even if the behavior is also explicitly specified as undefined or implementation-defined

Share:
10,722
Borja Tarraso
Author by

Borja Tarraso

Updated on June 04, 2022

Comments

  • Borja Tarraso
    Borja Tarraso almost 2 years

    Just curious why this code (that it is obviously wrong) using gcc it compiles, however the same code using the g++ it does not.

    int main()
    {
        char *foo = {"bar", "fred", "bob"};
    
        return 0;
    }
    

    gcc gives this warning but still compiles and generates the binary:

    % gcc -o x x.c

    x.c: In function ‘main’: x.c:3:5: warning: excess elements in scalar initializer [enabled by default] x.c:3:5: warning: (near initialization for ‘foo’) [enabled by default] x.c:3:5: warning: excess elements in scalar initializer [enabled by default] x.c:3:5: warning: (near initialization for ‘foo’) [enabled by default]

    % ls -l x

    -rwxr-xr-x 1 overdrive overdrive 6593 Jul 28 21:51 x

    g++ gives this error and no any binary as an output:

    % g++ -o y y.cpp

    y.cpp: In function ‘int main()’: y.cpp:3:38: error: scalar object ‘foo’ requires one element in initializer

    % ls -l y

    ls: cannot access y: No such file or directory

    gcc and g++ version I am using is:

    % g++ --version
    g++ (Debian 4.7.2-5) 4.7.2 Copyright (C) 2012 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    Is there any good reason why this compiles in gcc and not in g++? or it is clearly a bug?

  • Admin
    Admin almost 10 years
    No, "shall" does not mean "shall issue an error", it does not mean that at all. All that is required is a diagnostic. It does not have to be labelled "error", and once the diagnostic is issued, the standard places no further requirements on the implementation. The only time an implementation must not successfully translate a program is if it contains an #error directive.
  • Admin
    Admin almost 10 years
    Downvote removed, though I don't really think that answers the question: it just shows that both behaviours are valid, but it doesn't answer the question of whether it could be intentional or an accident.