What is the array initialization style in this code? Is it standard? - c++

I came across a source file here (in C). It uses a reasonable-but-strange style to initialize an array. I gave it a try in a shorter C++ program (please notice the "old way" in the code's comment):
arr.cc
#include <iostream>
using namespace std;
int main() {
long arr[] = { [0] = 100, [1] = 101 }; // old way: long arr[] = { 100, 101 };
cout << arr[0] << " " << arr[1] << endl;
}
The code is compiled like this:
g++-6 -std=c++14 arr.cc -o arr
When run, the output is this:
100 101
It passed with -std=c++14? But I can't find it in a C++ reference website, like cppreference.com. Does it conform to the standard? If so, since which version?

This is not valid C++ code; the C standard adopted it, and as an extension GCC allows it in C++ as well. To get GCC to conform to the C++ standard, you need to pass both -std=c++17 (or whatever version) and -pedantic. With that, your code does emit warnings saying it's nonstandard. The description of how this works in GCC is here.
Note that you can also do this with struct members, not just arrays; given
struct Point
{
int x;
int y;
};
you can say Point p = {.x = 17}. This is also nonstandard in C++ so far, but it will be adopted in C++2a. This only applies to the non-array version so far; I don't know if there are plans to add the array version as well or if it will happen by C++2a.

Related

Call Parameter as Reference to Array of Unknown Bound in C++

I am trying to understand whether references to array of unknown bound can be used as call parameter in functions in C++. Below is the example that i have:
EXAMPLE 1
void func(int (&a)[])
{
}
int main()
{
cout << "Hello World" << endl;
int k[] = {1,2,3};
// k[0] = 3;
func(k);
return 0;
}
To my surprise this example 1 above works when compiled with GCC 10.1.0 and C++11 but doesn't work with GCC version lower that 10.x. I don't think that we can have references to arrays of unknown size in C++. But then how does this code compile at the following link: successfully compiled
My second question is that can we do this for a function template? For example,
EXAMPLE 2
template<typename T1>
void foo(int (&x0)[])
{
}
Is example 2 valid C++ code in any version like C++17 etc. I saw usage of example 2 in a book where they have int (&x0)[] as a function parameter of a template function.
I don't think that we can have references to arrays of unknown size in C++.
That used to be the case, although it was considered to be a language defect. It has been allowed since C++17.
Note that implicit conversion from array of known bound to array of unknown bound - which is what you do in main of example 1 - wasn't allowed until C++20.
Is example 2 valid C++ code in any version like C++17
Yes; the template has no effect on whether you can have a reference to array of unknown bound.

Defining arrays with(out) constant expressions

I am slowly bringing myself up to c++11. I was looking at constexpr and stumbled into this wikipedia article which lead me to "something completely different". The basic example it gives is:
int get_five() {return 5;}
int some_value[get_five() + 7]; // Create an array of 12 integers. Ill-formed C++
It states "This was not legal in C++03, because get_five() + 7 is not a constant expression." and says that adding constexpr to the get_five() declaration solves the problem.
My question is "What problem?". I compiled that code with neither errors nor warnings. I played with it making it horribly non constant:
#include <iostream>
int size(int x) { return x; }
int main()
{
int v[size(5) + 5];
std::cout << sizeof(v) + 2 << std::endl;
}
This compiles with no complaints using:
g++ -Wall -std=c++03
and when executed I get the (correct) answer 42.
I admit that I generally use stl containers, not arrays. But I thought (and apparently so did wikipedia) that compilation of the above code would fail miserably. Why did it succeed?
Variable-length arrays (that is, arrays whose size is determined by a non-constant expression) are allowed in C, and some C++ compilers allow them as an extension to the language. GCC is one such compiler.
You'll get a warning if you compile with -pedantic or -Wvla, or an error with -pedantic-errors. Use those flags if you want to avoid non-standard compiler extensions.
As it has been said already some C++ compilers support C feature named Variable Length Array(s) whose sizes can be specified at run-time.
However VLA(s) may not be declared with static storage duration. The program you showed
#include <iostream>
int size(int x) { return x; }
int main()
{
int v[size(5) + 5];
std::cout << sizeof(v) + 2 << std::endl;
return 0;
}
can be compiled. However if you place the array outside any function then the code will not be compiled. Consider the following program that is similar to your original program with minor changes.
#include <iostream>
int size(int x) { return x; }
int v[size(5) + 5];
int main()
{
std::cout << sizeof(v) + 2 << std::endl;
return 0;
}
In this case the compiler will issue an error. However if you will specify constexpr for function size then the above program will be compiled successfully
#include <iostream>
constexpr int size(int x) { return x; }
int v[size(5) + 5];
int main()
{
std::cout << sizeof(v) + 2 << std::endl;
return 0;
}
The C++ Standard requires that sizes of arrays would be constant expressions.
8.3.4 Arrays [dcl.array]
1 In a declaration T D where D has the form
D1 [ constant-expressionopt] attribute-specifier-seqopt
and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is an array type;
Take into acount that not all C++ compilers (and even C compilers; for C compilers it is implementation defined whether a compiler supports VLA) have such a language extension as VLA. So if you want that your program would be C++ compliant then you should not rely on specific language extensions of a compiler.
Some compilers have extensions, which implement VLA (Variable Length Arrays).
Compile with -pedantic and you'll see the difference.

C++ GNU designated structure initialization not recognized in Eclipse

The CDT parser reports a syntax error for the structure initialization:
typedef struct MyStruct
{
int a;
float b;
};
int main( void )
{
// GNU C extension format
MyStruct s = {a : 1, b : 2};
// C99 standard format
// MyStruct s = {.a = 1, .b = 2};
return 0;
}
While GCC lists the : form as obsolete, it would seem that it has not been deprecated nor removed. In C99 I would certainly use the standard .<name> = form but for C++, the : is the only option that I am aware of for designated initialization.
I have tried setting my toolchain to both MinGW and Cross GCC, but neither seem to work.
How can I get Eclipse to recognize this syntax? It's not a big deal for one line but it carries through to every other instance of the variable since Eclipse does not realize it is declared.
The . form is only available in C99 and not in any flavor of C++. In C++ your only standards-compliant options are ordered initialization or constructors.
You can use chaining with appropriate reference returning methods to create a similar interface (here a and b are methods rather than variables):
MyStruct s;
s.a(1).b(2);
I meet this problems too and i use below method to solve it.
MyStruct s = {
1,
2,
}
This requires programmer to ensure sequence of initialization.

"const variables" set by a constructor for expressing the bounds of a C++ array?

The following code compiles and it seems to run fine:
class Test {
private:
const unsigned MAX;
public:
Test (const unsigned int n) : MAX(n) { }
void foo () {
int array[MAX];
...
}
};
but is it really OK? I mean:
Test a (3);
Test b (8);
does array actually have 3 and 8 cells respectively?
If so, is it because array is an automatic var and gets instantiated with the appropriate dimension?
Thanks
What you have written is valid in c99 but not valid c++.
I am of course talking about your use of VLA's, not the full snippet.
When compiling using g++ -pedantic -ansi -Wall we get the below warning;
foo.cpp: In member function 'void Test::foo()':
foo.cpp:18:23: warning: ISO C++ forbids variable length array 'array' [-Wvla]
As mentioned in the above warning the pattern you are using is often referred to as using a variable length array, which is standard in C99 and "allowed" in C++ through a g++ extension.
I'd recommend you to use a STL container instead of hacks as these, for one single reason; what you are doing is not legal, and therefor isn't guaranteed to be portable cross compilers.
Variable length arrays are not standard C++. You could make Test a template instead:
template <int MAX>
class Test {
public:
Test () {}
void foo () {
int array[MAX];
}
};
Test<4> t4;
Test<8> t8;
You are correct that this is not legal C++. If it works on your compiler, it is probably because you are using a GCC extension.

Are flexible array members valid in C++?

In C99, you can declare a flexible array member of a struct as such:
struct blah
{
int foo[];
};
However, when someone here at work tried to compile some code using clang in C++, that syntax did not work. (It had been working with MSVC.) We had to convert it to:
struct blah
{
int foo[0];
};
Looking through the C++ standard, I found no reference to flexible member arrays at all; I always thought [0] was an invalid declaration, but apparently for a flexible member array it is valid. Are flexible member arrays actually valid in C++? If so, is the correct declaration [] or [0]?
C++ was first standardized in 1998, so it predates the addition of flexible array members to C (which was new in C99). There was a corrigendum to C++ in 2003, but that didn't add any relevant new features. The next revision of C++ (C++2b) is still under development, and it seems flexible array members still aren't added to it.
C++ doesn't support C99 flexible array members at the end of structures, either using an empty index notation or a 0 index notation (barring vendor-specific extensions):
struct blah
{
int count;
int foo[]; // not valid C++
};
struct blah
{
int count;
int foo[0]; // also not valid C++
};
As far as I know, C++0x will not add this, either.
However, if you size the array to 1 element:
struct blah
{
int count;
int foo[1];
};
the code will compile, and work quite well, but it is technically undefined behavior. You can allocate the appropriate memory with an expression that is unlikely to have off-by-one errors:
struct blah* p = (struct blah*) malloc( offsetof(struct blah, foo[desired_number_of_elements]);
if (p) {
p->count = desired_number_of_elements;
// initialize your p->foo[] array however appropriate - it has `count`
// elements (indexable from 0 to count-1)
}
So it's portable between C90, C99 and C++ and works just as well as C99's flexible array members.
Raymond Chen did a nice writeup about this: Why do some structures end with an array of size 1?
Note: In Raymond Chen's article, there's a typo/bug in an example initializing the 'flexible' array. It should read:
for (DWORD Index = 0; Index < NumberOfGroups; Index++) { // note: used '<' , not '='
TokenGroups->Groups[Index] = ...;
}
If you can restrict your application to only require a few known sizes, then you can effectively achieve a flexible array with a template.
template <typename BASE, typename T, unsigned SZ>
struct Flex : public BASE {
T flex_[SZ];
};
The second one will not contain elements but rather will point right after blah. So if you have a structure like this:
struct something
{
int a, b;
int c[0];
};
you can do things like this:
struct something *val = (struct something *)malloc(sizeof(struct something) + 5 * sizeof(int));
val->a = 1;
val->b = 2;
val->c[0] = 3;
In this case c will behave as an array with 5 ints but the data in the array will be after the something structure.
The product I'm working on uses this as a sized string:
struct String
{
unsigned int allocated;
unsigned int size;
char data[0];
};
Because of the supported architectures this will consume 8 bytes plus allocated.
Of course all this is C but g++ for example accepts it without a hitch.
If you only want
struct blah { int foo[]; };
then you don't need the struct at all an you can simply deal with a malloc'ed/new'ed int array.
If you have some members at the beginning:
struct blah { char a,b; /*int foo[]; //not valid in C++*/ };
then in C++, I suppose you could replace foo with a foo member function:
struct blah { alignas(int) char a,b;
int *foo(void) { return reinterpret_cast<int*>(&this[1]); } };
Example use:
#include <stdlib.h>
struct blah {
alignas(int) char a,b;
int *foo(void) { return reinterpret_cast<int*>(&this[1]); }
};
int main()
{
blah *b = (blah*)malloc(sizeof(blah)+10*sizeof(int));
if(!b) return 1;
b->foo()[1]=1;
}
A proposal is underway, and might make into some future C++ version.
See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1039r0.html for details (the proposal is fairly new, so it's subject to changes)
I faced the same problem to declare a flexible array member which can be used from C++ code. By looking through glibc headers I found that there are some usages of flexible array members, e.g. in struct inotify which is declared as follows (comments and some unrelated members omitted):
struct inotify_event
{
//Some members
char name __flexarr;
};
The __flexarr macro, in turn is defined as
/* Support for flexible arrays.
Headers that should use flexible arrays only if they're "real"
(e.g. only if they won't affect sizeof()) should test
#if __glibc_c99_flexarr_available. */
#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
# define __flexarr []
# define __glibc_c99_flexarr_available 1
#elif __GNUC_PREREQ (2,97)
/* GCC 2.97 supports C99 flexible array members as an extension,
even when in C89 mode or compiling C++ (any version). */
# define __flexarr []
# define __glibc_c99_flexarr_available 1
#elif defined __GNUC__
/* Pre-2.97 GCC did not support C99 flexible arrays but did have
an equivalent extension with slightly different notation. */
# define __flexarr [0]
# define __glibc_c99_flexarr_available 1
#else
/* Some other non-C99 compiler. Approximate with [1]. */
# define __flexarr [1]
# define __glibc_c99_flexarr_available 0
#endif
I'm not familar with MSVC compiler, but probably you'd have to add one more conditional macro depending on MSVC version.
Flexible arrays are not part of the C++ standard yet. That is why int foo[] or int foo[0] may not compile. While there is a proposal being discussed, it has not been accepted to the newest revision of C++ (C++2b) yet.
However, almost all modern compiler do support it via compiler extensions.
GCC has zero length array extension which is supported for C++.
Clang aims to supports a broad range of GCC extensions.
MSVC has a non standard extension and a warning associated with it.
The catch is that if you use this extension with the highest warning level (-Wall --pedantic), it may result into a warning.
A workaround to this is to use an array with one element and do access out of bounds. While this solution is UB by the spec (dcl.array and expr.add), most of the compilers will produce valid code and even clang -fsanitize=undefined is happy with it:
#include <new>
#include <type_traits>
struct A {
int a[1];
};
int main()
{
using storage_type = std::aligned_storage_t<1024, alignof(A)>;
static storage_type memory;
A *ptr_a = new (&memory) A;
ptr_a->a[2] = 42;
return ptr_a->a[2];
}
demo
Having all that said, if you want your code to be standard compliant and do not depend on any compiler extension, you will have to avoid using this feature.
Flexible array members are not supported in standard C++, however the clang documentation says.
"In addition to the language extensions listed here, Clang aims to support a broad range of GCC extensions."
The gcc documentation for C++ says.
"The GNU compiler provides these extensions to the C++ language (and you can also use most of the C language extensions in your C++ programs)."
And the gcc documentation for C documents support for arrays of zero length.
https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
The better solution is to declare it as a pointer:
struct blah
{
int* foo;
};
Or better yet, to declare it as a std::vector:
struct blah
{
std::vector<int> foo;
};