Variable length arrays with initialization

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Variable length arrays with initialization

Hans Wennborg via cfe-dev
Hello list,

Given the following piece of code

int foo (int i) {
   char  array[i+1] = {0};

   if (array[i]) {
      return 0;
   }
   return 1;
}


When compiling with g++ [g++ (GCC) 6.4.0] the code compiles OK.

But when compiling with clang++ [clang version 4.0.1
(tags/RELEASE_401/final)] I get the following error.

array.c++:2:17: error: variable-sized object may not be initialize


My question now is, is this an bug in GCC, or is there an option for
CLANG to compile this code without errors? Or may is there an option for
g++ to let the compile fail on this code?


Frank
_______________________________________________
cfe-dev mailing list
[hidden email]
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
Reply | Threaded
Open this post in threaded view
|

Re: Variable length arrays with initialization

Hans Wennborg via cfe-dev
On Thu, Mar 8, 2018 at 2:47 AM, Frank Redeker via cfe-dev
<[hidden email]> wrote:

> Hello list,
>
> Given the following piece of code
>
> int foo (int i) {
>    char  array[i+1] = {0};
>
>    if (array[i]) {
>       return 0;
>    }
>    return 1;
> }
>
>
> When compiling with g++ [g++ (GCC) 6.4.0] the code compiles OK.
>
> But when compiling with clang++ [clang version 4.0.1
> (tags/RELEASE_401/final)] I get the following error.
>
> array.c++:2:17: error: variable-sized object may not be initialize
>
>
> My question now is, is this an bug in GCC, or is there an option for
> CLANG to compile this code without errors? Or may is there an option for
> g++ to let the compile fail on this code?

C17 6.7.9p3 says:
The type of the entity to be initialized shall be an array of unknown
size or a complete object type that is not a variable length array
type.

Clang is correct to diagnose that code. When I try out various
versions of GCC, they also diagnose your code example
(https://godbolt.org/g/Djf5iG) so I'm not certain what's happening
with your version of GCC.

~Aaron

>
>
> Frank
> _______________________________________________
> cfe-dev mailing list
> [hidden email]
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
_______________________________________________
cfe-dev mailing list
[hidden email]
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev