10,429 questions
4
votes
2
answers
133
views
Error with creating an array of named/predefined string constants in c
For background, I am working to create a version of minesweeper that runs in the terminal to become more familiar with coding bigger projects in c.
I am coding in VScode, to run on a Linux server (...
2
votes
1
answer
113
views
Accessing Union Members with Different Qualifiers in C
In the C standard (at least, I'm looking at draft C23 WG14/N3088), section 6.7.3 Type Qualifiers states:
7 If an attempt is made to modify an object defined with a const-qualified type through the ...
6
votes
2
answers
282
views
How do I follow "C.12 - Don’t make data members const or references in a copyable or movable type" while keeping track of some const value?
When I have some const members variables in my class, I would like to know how to respect core guideline C.12 to keep a default copy-assignment operator.
C.12: Don’t make data members const or ...
0
votes
2
answers
166
views
How can I implement periodic output in a const method with irregular time steps and no internal state?
I have a time domain simulation running timesteps are adaptive and may grow or shrink, so there aren't a fixed number of steps to a constant time.
I want to produce an output every (simulation) time ...
3
votes
3
answers
199
views
Is a function call returning a pointer a prvalue?
This question arouse from the question "why is const in function return type, which is a const pointer, ignored?" (const pointer, not pointer to const)
int* const Foo();
is identical to
int*...
2
votes
1
answer
142
views
In Rust is it possible to use a pseudo random number generator with a seed in a const context?
I'm writing a chess engine in Rust and want to start using Zobrist Hashing, which requires me to pre-initialize an array of pseudo-random numbers from a constant seed.
Since this array won't change, I ...
8
votes
2
answers
274
views
Why should I be careful in "noexcept-ing all the functions" just like I "const all the things"?
I haven't found a video about const all the things ¹, but there's at least Con.3: By default, pass pointers and references to consts from the Cpp Core Guidelines.
There's lots of presentations and ...
12
votes
1
answer
297
views
C++ temporary objects and constant reference
I am going through "C++ Primer", and it is mentioned that for the following code:
double dval = 3.14;
const int &ri = dval; //Bind a const int to a plain double object.
The ...
2
votes
2
answers
179
views
How does interpolating a Perl constant into a string work?
I've just come across such usage of Perl constants:
use strict;
use warnings;
use constant PI => 4 * atan2(1, 1);
print("The value of PI is: ${\PI}\n"); # The value of PI is: 3....
8
votes
1
answer
155
views
Are empty structs constant expressions?
The following code compiles on all the compilers that I tested so far:
struct Alignment {
struct Center {
constexpr Center() {}
};
static const Center CENTER;
};
constexpr int foo(...
5
votes
0
answers
144
views
How do I get CLion to prefer T const& over const T&?
CLion supports a "code inspection" named "pass value parameters by const&", which suggests you prefer passing by const& rather than by-value with a copy.
When you accept ...
-3
votes
2
answers
149
views
What are the actual benefits of returning a constant value from a function/method? [duplicate]
I tried to use constants when returning a value from a function/method, but I don't see any benefits of using it because we can't modify the returned value from inside a function. Or even from outside....
1
vote
0
answers
29
views
Cannot index const object by known property in TypeScript [duplicate]
I have a complex but well-typed constant object such that no matter what the first and second level keys are, there is always a particular known key at the third level (in the example below, moons). ...
0
votes
1
answer
95
views
PHP vs C++: How do I declare class constants which are used in method calls in C++? [duplicate]
I come from PHP where I usually never have global constants. For instance, if I have the class Users and the method add(int $status, string $username) then the status of the user is a constant only ...
5
votes
5
answers
420
views
Why Zero has no decimal integer spelling in C?
I am reading modern C, and on page 66, I come across following section:
Remember that value 0 is important. It is so important that it has a lot of equivalent
spellings: 0, 0x0, and ’\0’ are all the ...
2
votes
1
answer
136
views
Must T be unqualified in std::allocator<T>?
gcc, clang, and msvc all reject the following code:
#include <memory>
#include <vector>
int main() {
auto _ = std::vector<int const>{}; // error
auto _ = std::vector<...
4
votes
2
answers
164
views
Is assigning string literal to mutable char* legal on newer language revisions or just warned against by compilers?
Related to Is it bad to declare a C-style string without const? If so, why? , but that question is about best practise, while mine is more language lawyer. Similar questions have been asked, but for C+...
9
votes
2
answers
743
views
Why does the tuple hash function itself, i.e., operator(), need to be const?
I am trying to make an std::unordered_set whose key is of type std::tuple.
The below code compiled by MSVC gives me:
Error C3848 expression having type 'const _Hasher' would lose some const-volatile ...
3
votes
2
answers
93
views
Should I care about Wcast-qual errors?
I recently read the NASA's power of 10 rules, and thought the rule about "using the compiler's most pedantic setting" was very interesting, considering warnings exist for a reason. I already ...
1
vote
1
answer
140
views
How does U32C in ChaCha20 bypass endianness concerns?
While reading the ChaCha20 cipher's source code, I noticed something unusual. The algorithm's constants (like 0x61707865) aren't converted for endianness, yet this doesn't cause issues across ...
2
votes
2
answers
129
views
Disparity in errors on passing const-argument value to a non-const parameter of a function in C++
I was trying to understand the use of 'const' keyword with pointers from the source: GeeksforGeeks.
It is mentioned that "Passing const argument value to a non-const parameter of a function isn't ...
1
vote
2
answers
184
views
How to create a constant generic array of strings with other constants in Delphi? (Error: Constant expression expected)
This answer shows that you can create a constant generic array of strings. So this code works:
const AllTestJSON: TArray<String> = [
'''
[
{'Computer Webcam', TAlphaColors.Aliceblue},...
1
vote
1
answer
159
views
C++ builtin constexpr vs CUDA __constant__ for higher dimension array
I recently need to implement a Sobol sequence generator by CUDA.
Now to pre-store the Sobol table, I can either use a C++ native constexpr like below:
constexpr unsigned int sobol_table[NUM_DIMENSIONS]...
3
votes
2
answers
138
views
calling function with variable argument list using const arguments
Does any of the C Standards describe any kind of a check to ensure that const is used and accessed appropriately with variable argument lists?
If I have the following source for a function with a ...
1
vote
0
answers
68
views
Passing newly created const-qualified objects as array indexes (or slices) requires parentheses
I encountered a situation when a newly created const-qualified std::valarray<size_t> is passed to another std::valarray’s subscript operator [] when defining a std::indirect_array. This worked ...
0
votes
0
answers
31
views
Problems calling classes in VBA for Excel [duplicate]
I have a class called Astro that has a list of variables for a body some of which are calculated. In the class module:
Public Mass as Double
Public GM As Double
Public Sub Calculate()
Mass = GM / 6....
6
votes
4
answers
208
views
Initialize constant string array out of order [closed]
Trying to increase robustness of a piece of embedded code - simplified like this:
enum tags {
TAG1,
TAG2,
NUM_TAGS
};
const char* const vals_ok[] = { "val1", "val2" };
...
1
vote
1
answer
90
views
Is it valid to initialize a struct with const members allocated on the stack with alloca?
Considering that the type A is defined like this:
typedef struct a { const int a; } A;
I know that this code is valid:
A * foo = malloc(sizeof *foo); // Allocates uninitialized memory with no ...
9
votes
1
answer
269
views
Cannot match on Result in const fn due to "destructor cannot be evaluated at compile-time" even when value isn't dropped
I tried to match on a generic Result<&mut T, T> inside of a const fn, but the compiler did not let me. It would require being able to drop the value at the end of the scope, which is
...
1
vote
3
answers
178
views
How can I implement true constants in Python?
I'm attempting to use real constants in Python—values which cannot be modified once defined.
I realize Python has no native support for constants like certain other languages (e.g., final in Java or ...
0
votes
1
answer
97
views
Constant Declaration Conventions
So far I've been declaring my constants in the "Main" module for my workbook, below the "Option Explicit" but above the "Sub DoTheWork()."
Do public constants have to be ...
-4
votes
2
answers
201
views
Ordinary pointer to const variable in C? [closed]
My Q: Was it possible in older compilers?
Creating an ordinary pointer to a const variable in C. I saw some ytuber (2016), but now the code doesn't compile.
Following code now gives error (which is OK)...
6
votes
2
answers
255
views
Design pattern for const structures?
Let's say I have to read some configuration files to set fields of a structure. As soon as the file has been read and the structure initialized, its field's values should not be changed.
I read many ...
7
votes
1
answer
96
views
Why does this code not use the template specialization or fail with ambiguous calls?
This code prints Upper, although I would want it to print Lower:
#include <concepts>
#include <iostream>
struct X {
explicit operator bool() const { return true; }
};
template<...
1
vote
3
answers
233
views
Does declaring an unused const variable in C lead to undefined behavior?
I know that unused variables in C typically just lead to compiler warnings, and const variables are meant to be read-only.
However, I’m curious: according to the C standard, is there any scenario ...
2
votes
1
answer
91
views
Why does this function pointer typedef behave differently when used with const?
#include <stdio.h>
typedef int (*func_t)(int);
int foo(int x) {
return x * 2;
}
int main() {
const func_t ptr = foo; // Works
//const func_t *ptr = &foo; // Fails: why?
...
1
vote
2
answers
94
views
Why is it allowed for a const pointer to be passed as non-const argument of a function and get modified?
I am able to pass a const pointer as argument of a function that takes non-const pointer.
Furthermore, inside the function body, I was allowed to modify its value as well with only a warning:
(passing ...
0
votes
1
answer
67
views
How to target ID on a specific tag in JS? [duplicate]
I want to target an ID on my sdf-carousel-item in the code below.
const carouselModal = document.querySelector("sdf-carousel-item");
const carouselSlideOne = carouselModal.querySelector("#first"...
0
votes
1
answer
113
views
Pass parameters to exe-file (compiled from Simulink)
I have a simple Simulink model that passes a constant variable to the workspace.
I've converted the Simulink model to an exe-file using Simulink Coder (with grt.tlc as the target system file). ...
1
vote
0
answers
75
views
Why is `operator=` automatically casting to `const type` [duplicate]
When I use this code:
#include "promise.hpp"
#include <thread>
using namespace std;
int main() {
stsb::promise<int> tstint = stsb::promise<int>();
thread waitthr = ...
3
votes
2
answers
115
views
What is the const qualifier attached to in C: the memory area or the pointer?
I wondered, if the const qualifier in C is the attribute of the pointer or the memory area?
If I do something like:
struct S { int data; }
struct CS { const int data; }
char *p = malloc(100);
struct ...
0
votes
2
answers
136
views
Set Const or static readonly field value from appsettings.json through dependency injection in .net core 9
I have this MagicSgtrings class that holds some constants which I'm using in my worker service.
internal class MagicStrings
{
public const string HttpClientName = "X_HttpClient";
...
}
...
2
votes
2
answers
120
views
Are string-backed enums useful as string constant dumps in PHP?
In order to get in touch with PHP, I began a little website project from scratch.
The project steadily grew so that now, I'm refactoring my codebase.
Up until now, I made use of constants which I use ...
1
vote
2
answers
1k
views
How should one migrate from lazy_static to std LazyLock/LazyCell
I created a library that uses lazy_static to create a static HashMap that other parts of the code can reference to look up values like this:
use lazy_static::lazy_static;
use std::collections::HashMap;...
1
vote
1
answer
114
views
Why can't I declare class-scope constants without using 'static'? [duplicate]
I'm an OOP newbie and just learning classes. Why can't I create constants and use them in classes without the static specifier? Like this:
class MyClass{
private:
const int MyConst = 10;
int ...
0
votes
4
answers
186
views
const qualifier on struct
If I have the following code:
struct point
{
int x;
int y;
};
const struct point p = {1, 2};
p.x = 3;
The compiler gives me an error: "assignment of member 'x' ...
1
vote
0
answers
95
views
Rust ndarray, statically allocate an array
I have an ndarray array that is used throughout my program:
Note: ndarray and nalgebra are both used here, imported as nd and na respectively.
let test: nd::ArrayBase<nd::OwnedRepr<na::...
1
vote
1
answer
61
views
Struct field with multiple const types
Say I have a const type and corresponding sub types -
type Animaltype int32
const (
dogs Animaltype = iota
cats
)
type dogtype int32
const (
retriever dogtype = iota
whippet
)...
2
votes
3
answers
159
views
Lazy initialization of const attributes in c++
I would like to carry out a lazy initialization of a set of (std::vector) attributes in c++. They have to be const, in the sense that after the first time they are initialized (via a get method), ...
0
votes
0
answers
66
views
Const correctness on returning unmodified C string [duplicate]
I was writing this function which I think is self-explanatory:
char *palindromeFirstMismatch(char *s) {
char *e = s + strlen(s) - 1;
while (s < e && *s == *e)
++s, --e;
if (s >=...