Declare a Const Array

Declare a const array

Yes, but you need to declare it readonly instead of const:

public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };

The reason is that const can only be applied to a field whose value is known at compile-time. The array initializer you've shown is not a constant expression in C#, so it produces a compiler error.

Declaring it readonly solves that problem because the value is not initialized until run-time (although it's guaranteed to have initialized before the first time that the array is used).

Depending on what it is that you ultimately want to achieve, you might also consider declaring an enum:

public enum Titles { German, Spanish, Corrects, Wrongs };

How to define a const array in typescript

As you point out the issue is cause because you try to assign the string array (string[]) to a 7-string-tuple. While your solution to use any will work it's not generally advisable to use any. Spelling out the supple is also not ideal since it's soo long.

What we can do is create a helper function to create a tuple type. This function is reusable for anywhere you need tuple:

function tupleArray<T extends any[]>(...v: T) {
return v;
}
const WEEKDAYS_SHORT_INFFERED = tupleArray('Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam') // INFFERED AS [string, string, string, string, string, string, string]
const WEEKDAYS_SHORT: [string, string, string, string, string, string, string] = WEEKDAYS_SHORT_INFFERED

Const array of strings

Declare it as readonly instead of const:

public readonly string[] names = { "alpha", "beta", "gamma", "delta" };

What do we mean by defining a const array in js?

Declaring a variable as const only means that you cannot assign a new value to that variable once a value has been assigned:

const array = [];

array = []; // Not allowed: assignment to constant variable

Declaring an array as const has no bearing on what you can do with the contents of the actual array:

const array = [];

array.push("something"); // Allowed: add value to array
array[0] = "or other"; // Allowed: replace value in array
array.length = 0; // Allowed: change array size

Declare a constant array

An array isn't immutable by nature; you can't make it constant.

The nearest you can get is:

var letter_goodness = [...]float32 {.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007 }

Note the [...] instead of []: it ensures you get a (fixed size) array instead of a slice. So the values aren't fixed but the size is.

As pointed out by @jimt, the [...]T syntax is sugar for [123]T. It creates a fixed size array, but lets the compiler figure out how many elements are in it.

Const arrays in C

It means that each element of z is read-only.

The object z is an array object, not a pointer object; it doesn't point to anything. Like any object, the address of z does not change during its lifetime.

Since the object z is an array, the expression z, in most but not all contexts, is implicitly converted to a pointer expression, pointing to z[0]. That address, like the address of the entire array object z, doesn't change during the object's lifetime. This "conversion" is a compile-time adjustment to the meaning of the expression, not a run-time type conversion.

To understand the (often confusing) relationship between arrays and pointers, read section 6 of the comp.lang.c FAQ.

It's important to understand that "constant" and const are two different things.

If something is constant, it's evaluated at compile time; for example, 42 and (2+2) are constant expressions.

If an object is defined with the const keyword, that means that it's read-only, not (necessarily) that it's constant. It means that you can't attempt to modify the object via its name, and attempting to modify it by other means (say, by taking its address and casting to a non-const pointer) has undefined behavior. Note, for example, that this:

const int r = rand();

is valid. r is read-only, but its value cannot be determined until run time.

How to correctly declare a const string array?

The function in question, posix_spawn, expects a pointer to (the first element of) an array of pointer to non-const char. Despite this, the function does not modify the character strings.

For historical reasons this situation of poor const-correctness in C APIs is not uncommon.

You can pass string literals to it without any warning in Standard C, because string literals have type: array of non-const char. (Modifying them is undefined behaviour with no diagnostic required).

If you use the -Wwrite-strings flag to try and get warnings about potential UB then it will give you these false positives for the cases where you interact with a non-const-correct API.


The intended way to consume the API in C89 would be to use:

char exe[] = "/usr/bin/some/exe";

char * argv[] = {
NULL,
"-a",
"-b",
NULL
};

argv[0] = exe;
show(argv);

Note that in C89 it is not possible to have your array be const and also be initialized with the local variable exe. This is because C89 requires all initializers in a braced list to be constant expressions, the definition of which excludes the address of a local variable.

If you want to use -Wwrite-strings then you could suppress the warning by using (char *)"-a" instead of "-a" and so on.


It was suggested in comments to use const char * for the string type and then use a cast, like so:

const char exe[] = "/usr/bin/some/exe";

const char * argv[] = {
NULL,
"-a",
"-b",
NULL
};
argv[0] = exe;
show((char **)argv);

However this probably violates the strict aliasing rule. Even though the rule allows a const T to be aliased as a T, this rule does not "recurse" ; it is probably not allowed to alias const char * as char * , although the rule's wording is not 100% clear. See this question for further discussion.

If you wanted to offer a wrapper that accepts const char ** and calls posix_spawn , and not violate the C Standard, then you would actually have to make a copy of the pointer list into an array of char *. (But you do not have to actually copy the string content)

Declaring an array with const keyword Javascript

const str = 'abcd';
str = 'changed'; //error

const list = [1,2,3]; // Assume this array is created on memory loc 0x001 (imaginary)

list[0] = 200; // no error here the memory location remains constant but the content changes.

list = [6,4,2]; // error Here new assignment hence memory location changes so error

Arrays or objects are mapped by location and not value compared to strings/numbers.

How To Declare Static Const Array

As far as I know you can't have in-class initializer for your static const std::string [].

You should initialize it outside the class declaration.
For instance:

#include <string>
class Foo
{
public:
static const std::string brands[];

};

// in your Foo.cpp file
const std::string Foo::brands[] = {"Coca-Cola","Pepsi","Ruffles"};


Related Topics



Leave a reply



Submit