1,595 questions
Best practices
1
vote
3
replies
133
views
Lost in uint8_t[] literals and std::span
I have the following very simplified C++26 code sample:
class i2c_request {
public:
constexpr i2c_request(std::uint8_t address, std::span<const std::uint8_t> request) noexcept:
...
2
votes
1
answer
95
views
Typescript infer real entries from object literal dictionary
I have a dictionary object, very simple:
const mydict = {
key1: "value1",
key2: "value2"
}
how do I make a type that automatically converts an object like this into entries?
...
3
votes
1
answer
106
views
How does Rust lexer handle the integer literal?
The following lex rules are copied from int_literal in docs of rust nightly.
INTEGER_LITERAL ->
( DEC_LITERAL | BIN_LITERAL | OCT_LITERAL | HEX_LITERAL ) SUFFIX_NO_E?
DEC_LITERAL -> ...
0
votes
2
answers
173
views
Exhaustively check for all literals while allowing for type inference of the return type
I’m trying to write a Python function that satisfies three goals simultaneously:
Exhaustively checks all possible values of a Literal argument.
Avoids linter warnings like Ruff’s "too many ...
1
vote
1
answer
56
views
Chaining two mapped object types leads to undesired union & intersection issues
I have two parametrized maps where the result of the first map for any key (context) matches with the required inputs for the second one of the associated context. How can I get typescript to check ...
6
votes
1
answer
141
views
Rules on the choice of type for a literal whose value is too big
I was testing the behaviour of the big three (GCC, clang, MSVC).
I'm not sure what is standard-compliant.
Consider this code:
// p43.cxx
#include <type_traits>
constinit auto n1 = ...
1
vote
1
answer
105
views
Haskell arithmetic with literals
In Haskell, a standalone expression 3 + 5 means fromInteger (3 :: Integer) + fromInteger (5 :: Integer). In GHCi it is evaluated to fromInteger 8 of type Num a => a. It is clear that Haskell can ...
5
votes
1
answer
162
views
Memory address of integer literals via ref in C++
#include <iostream>
using namespace std;
int main()
{
// Case 1
cout << &5; // This line fails to compile. Ok, I get this because "5" is a rvalue.
// Case 2
...
1
vote
2
answers
81
views
Type mismatch in Go generics with mixed untyped arguments
func sum[T int | float64](a, b T) T {
fmt.Println("Type of a: ", reflect.TypeOf(a))
fmt.Println("Type of b: ", reflect.TypeOf(b))
return a + b
}
type Pair[K, V any] ...
2
votes
3
answers
292
views
Why can't -2147483648 represented in hex literal?
Based on C++ documentation the size to hold hex literal grows from int -> unsigned int -> long -> unsigned long -> long long -> unsigned long long.
But I wonder how to specify hex ...
1
vote
1
answer
121
views
Compile-time check for -fsingle-precision-constant
I learned from the accepted answer to
Make C floating point literals float (rather than double) and it's discussion,
GCC provides the compiler flag -fsingle-precision-constant to force floating point ...
4
votes
8
answers
289
views
Grouping sets of 4 bits into nybbles in C printf
C23 added support for binary literals (0xb10100110) and for grouping them for human readability using a separator character ('). This is great for input, but how does one change the printf grouping to ...
1
vote
2
answers
231
views
Difference between a mutable and immutable string [duplicate]
I just started studying C++, but there is a thing that I don't fully understand: when you initialize a std::string variable with a string literal, like this:
std::string str = "some string";
...
0
votes
1
answer
38
views
mockito test data from val to literals springboot
i made a unit test, it works fine. Now i got a task to change the data from variables in the test body to literals, to make it more readable. So i did and got problem:
this test passes successfully:
...
2
votes
1
answer
131
views
How to insert literals in a colon definition?
I wrote a Forth interpreter for the J1 CPU, which I am now porting to Z80. In the new version, a colon word is a list of addresses to be called by the interpreter.
My problem is how to insert literals ...
0
votes
1
answer
398
views
Can you concatenate array literals at compile time in rust? [duplicate]
is there any way to concat array literals in rust?
For example, I want an array like [0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 9]
I can define an array [0; 8] and a [6, 9], but is there any way to write this ...
0
votes
2
answers
104
views
Convert `(String, Int)...` variadic parameter function to Dictionary for ExpressibleByDictionaryLiteral
I have objects that are currently initialized via one-parameter init functions that take an Array or Dictionary.
I've realized that I can use ExpressibleByArrayLiteral and ...
0
votes
1
answer
144
views
How do I use a literal C char constant in a comparison with Cython?
This seems rather trivial, but I couldn't find the answer myself: How do I use a literal C char constant in a comparison with Cython?
This doesn't work:
cdef fct(char c):
return c == 'x'
sh$ ...
0
votes
1
answer
158
views
TypeScript string literal type or enum [duplicate]
When should I create enum or use string literal type ?
String literal type:
export type Person = {
id : number,
name : string,
gender : "male" | "female"
}
Enum:
...
-2
votes
1
answer
82
views
Unterminated regexp literal at <h1>About</h1>
I use this sample code from Custom handlers | Fresh docs:
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = {
async GET(_req, ctx) {
const resp = await ctx....
3
votes
3
answers
294
views
How to check if a macro argument is an integer literal in C
I'm trying to do a macro like this:
#define STRING(i) \
struct STRING##i \
{ \
size_t len; \
char chars[i]; \
}
but the problem is this works with constexpr arguments like this:
constexpr int ...
3
votes
2
answers
286
views
How to define a comptime array of arrays of divergent size
I am very new to zig and doing a very simple coding exercise. The question is about scoring words in scrabble and presents a table. As a sort of challenge I wanted to replicate the scoring table as an ...
0
votes
2
answers
256
views
Should I use INT64_C as "int64_t literal" ...?
How can I write portable code to compare a constant integer value with an int64_t variable across different platforms (MacOS and Ubuntu)?
int64_t a = 2;
std::min(1, a);
Fails to compile on MacOS when ...
0
votes
0
answers
156
views
Create a localized string with a generated comment
My framework contains a protocol that allows conforming types to describe themselves. One of its requirements is a static member containing the name of the type. This can be used as (for example) the ...
-1
votes
1
answer
167
views
(ValueError: invalid literal for int() with base 10)
total = {}
count = 0
while(count < 4):
_input = input()
count = count + 1
total[_input] = 0
for i in range(5):
_input2 = int(input())
total[_input] = total[_input] + ...
2
votes
2
answers
919
views
Python - Passing enum set to Literal
I have a question about this construct:
from enum import Enum
from typing import Literal
class Fruit(Enum):
Apple = "apple"
Bannana = "bananna"
Watermelon = "...
2
votes
1
answer
1k
views
pydantic validate all Literal fields
I have multiple pydantic 2.x models and instead of applying validation per each literal field on each model
class MyModel(BaseModel):
name: str = ""
description: Optional[str] = None
...
0
votes
0
answers
38
views
Suffixes for numerical constants in C: when should they be used? [duplicate]
I've used C for scientific programming for more than 15 years and I've never needed suffixes like F and L for numerical literals. I wonder why some very experienced programmers almost always use them....
0
votes
1
answer
126
views
What are the differences among L'\x1234', '\u1234', u'\x1234' and L'\u1234' in C?
What are the differences among L'\x1234', '\u1234', u'\x1234' and L'\u1234' in C (C11 and newer versions)?
Apparently a character constant with prefix L is of type wchar_t and a constant with prefix u ...
0
votes
2
answers
978
views
C Programming - What is 2U or 8U in struct
Code from this link: https://github.com/openwch/arduino_core_ch32/blob/main/libraries/USBPD_SINK/src/usbpd_def.h
I am looking at the previous file. I did some search and found something about unsign ...
6
votes
3
answers
669
views
Writing the smallest (signed) 32-bit number as a C++ literal
If I wished to use the <limits> header, it would be easy to write the smallest integer:
std::int32_t small = std::numeric_limits<std::int32_t>::min();
This makes small equal to -...
-1
votes
1
answer
588
views
Using class variables for literal values
This is more of a request for comments and critique rather than a proper question.
Context: I am using simple classes with class variables as containers for string constants. These might hold ids of ...
0
votes
1
answer
222
views
Lifetime of literal values inside Zig comptime function
Literal's lifetime inside a function
In the following code, is the reference returned by the function a bad pointer ?
fn hello() *const u8 {
return &'A';
}
No, because the 'A' literal has a ...
-3
votes
1
answer
3k
views
Python3 elevenlabs ImportError: cannot import name 'Literal' from 'typing'
enter image description here
See image. What am i doing wrong? I'm a newbie with python, i don't have a clue what i am doing wrong
ps: i previously installed the package elevenlabs with 'pip3 install ...
0
votes
1
answer
1k
views
Zig - Initializing a slice literal of union enum
I have the following types:
const ParsedValType = enum { String, Integer, List, Dict };
const ParsedVal = union(enum) {
String: []const u8,
Integer: i64,
List: []const ...
0
votes
2
answers
172
views
Escaping dot in if-statement with echo in Windows batch
I have a chicken-and-egg issue: I need to echo a dot in an if statement in a batch script, but the command prompt crashes, saying '. was unexpected at this time.'
Note that echoing treats everything ...
0
votes
1
answer
79
views
Python pattern match on an operator
I'm trying to build a function that would match on a operator , like - :
def testM(x):
match x:
case (operator.sub,a,b):
return operator.sub(a,b)
case ('-',a, b):
...
1
vote
1
answer
142
views
String Duplication
I wonder, is there another solution to modify to string literals and Is the solution really valid and optimal?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *...
2
votes
1
answer
148
views
How do I get PowerShell script path of and inside Batch-Powershell Hybrid script even when the path contains multiple occurrences of Square Brackets?
See the below script that I have for renaming Movie files with .mp4 or .mkv extensions:
<# ::
@echo off
powershell -c "iex ((Get-Content -LiteralPath '%~f0') -join [Environment]::Newline); ...
-1
votes
1
answer
80
views
Advantages and differences between passing string literals or const char[] to functions [closed]
let's say i have a program where i print the same line to the console multiple times throughout it's execution and the line needs to be passed to printf() multiple times.
on the surface the option at ...
0
votes
3
answers
150
views
What is a good way of initializing a vector of char* from string literals?
Until C++11, one was able to write the following:
#include <vector>
using namespace std;
int main_under_test(int argc, char* argv[]) {
return 0;
}
int main() {
vector<char*> args ...
0
votes
1
answer
120
views
How to render template literals without using new Function because chrome extension manifest v3 does not permit unsafe-eval
I made a chrome extension with the v2 manifest that uses a lot of template literals coming from json files. I was rendering them using new Function which made it so easy. But with chrome extension ...
0
votes
1
answer
60
views
Conditionally adding to an object literal in javascript [closed]
I would like to conditionally fill a property based on the target type.
I need to do this inside an event handler for a form (react).
I would like an if/else statements situations that encompasses ...
19
votes
2
answers
3k
views
C++23: char now supports Unicode?
Does C++23 now provide support for Unicode characters in its basic char type, and to what degree?
So on cppreference for character literals, a character literal:
'c-char'
is defined as either:
a ...
0
votes
4
answers
183
views
unsigned long long resTestBad = 0xffffffff + 1; print 0 with %llu, but unsigned long long resA = 4294967295 + 1; print 4294967296 with %llu
It seems that I found a bug when print value of (0xffffffff + 1) with %llu is 0, see below code:
unsigned long long resTestBad = 0xffffffff + 1; // number of f is 8
printf("resTestBad is %llu, ...
2
votes
4
answers
359
views
Why are string literals lvalues and not xvalues?
Ben Saks in his lesson "Understanding Value Categories" at the 2019 CppCon in Aurora (CO) (great lesson btw) said:
"Character string literals, such as "examplestring", are ...
1
vote
1
answer
645
views
SyntaxError: invalid decimal literal (gdrive)
user_interactions_df = pd.read_csv(https://drive.google.com/uc?export=download&id=1WgjXneyZHGQrxrh1maRyPdbXE3J9wp--)
...
3
votes
2
answers
184
views
An unsigned int literal outside bounds
If I define a variable of the unsigned int type and initialize it with a value outside its bounds, it uses modulo and assigns itself a value in its range, right?
For example:
unsigned int a = ...
1
vote
1
answer
332
views
What is the point of types of literals in C++?
I'm new to C++ and I'm using C++ Primer to study.
To me, it makes sense for variables to have "sub-types" like long and long long for int, so that they can accommodate larger values, even if ...
2
votes
1
answer
916
views
Can rust slice type [T] be used without reference or pointer?
The line assigning arguably a slice literal
let integers: [i32] = [ 1, 2, 3 ][..];
gives a message that integers “doesn't have a size known at compile-time”. Why is it not obvious that storage space ...