r/cpp_questions

How to start C++

Basically im in school and they use visuals studio code. I only have a laptop and no idea of Programming honestly. Should i install Linux? Probably a program clichee to ask this haha

reddit.com
u/Terrible_Month_9213 — 3 hours ago

Trouble replicating the Pokémon Damage formula

For starters, let me say that I am very new to programming. I'm finishing my first semester of college in a couple weeks and I decided to try and use the skills I learned from my fundamentals of programming class for one of my more recent hobbies, playing the newly released Pokémon Champions. Since I am a beginner, my code DEFINITELY is not optimal lol

Anyways, my goal was to make a program that could calculate how much damage one Pokémon would do using a move against another Pokémon, and then loop through that calculation with different stats to see the minimum amount of stats I need to train the Pokémon in to survive that move. For starters, I tried to see if I could just replicate the damage formula, but I'm running into a problem and I can't figure out why.

As a test, I put in the stats for Incineroar using Flare Blitz against Mega Froslass, and then printed out all 15 random damage values it could do. However, while some of these random values matched the damage calculator I was referencing against, some did not, being just barely off, and I cannot figure out why. I assume I am rounding wrong somehow but no matter how I tried tweaking it, I couldn't figure it out. I would really appreciate any help!

My Code: https://onlinegdb.com/NzSzWv1nT

Expected Results: 206, 210, 212, 216, 216, 218, 222, 224, 228, 228, 230, 234, 236, 240, 242

Damage Formula (Scroll Down to "Generation V onward": https://bulbapedia.bulbagarden.net/wiki/Damage

reddit.com
u/AuthorsThatJigs — 20 hours ago

can a generic lambda have a value template parameter?

I tried writing some code using generic lambdas, and in my case it would've been useful to have a value parameter for the lambda template. I don't have the code in front of me, but a simplified version had a line like:

auto foo = []<int y>(int x){return x * y;};

I get no compile errors on this line. However, I can't figure out how to provide the value parameter. A line like this gives an error about "no match for the operator '<'".

auto i = foo&lt;5&gt;(3);

If I remove the &lt;5&gt;, then the compiler can't deduce a value for y.

In case it matters, I was trying to use the lambda as a parameter to std::find_if. I've since refactored the code for cleaner logic (also targeting C++ 11, so no generic lambdas now), but I'm curious about whether it should have worked, and if so how.

reddit.com
u/pfp-disciple — 16 hours ago

Binary comparison for big ass multi level nested structures

Heyaa,

So recently I had to compare binaries in the layout of multi level nested big fat structures. I surprised to find that there are no good tools to do that. The best i could find was watch section in visual studio. I have tried another tool, WinDbg this doesn’t work well with macros and arrays. To make matters worse, this big ass structure has offsets that point beyond of the structure. How do you debug here? There is no good tools which automatically tells values for each field or was not keen enough to find such tool?

Tldr: i have custom buffer layout with multiple nested level structures. Want to find a tool that helps the debug.

reddit.com
u/dckdza — 19 hours ago

Is there a modern C++ alternative to flexible array members for variable-length struct tails?

Building a cache-optimized skip list where nodes have a variable number of forward pointers depending on their level (determined probabilistically at insertion). My naive approach was `std::array<Node*, MAX_LEVEL>` but that wastes memory since a level-1 node still allocates 16 pointer slots, most of which are nullptr. At scale this killed cache density significantly.

Currently using a C flexible array member:

struct Node {
    K key;
    V value;
    int level;
    Node* forward[];  // flexible array member
};

// allocate with extra space for forward pointers
void* mem = pool.allocate(sizeof(Node) + lvl * sizeof(Node*));
Node* n = new (mem) Node(k, v, lvl);

This works great. one contiguous allocation, forward pointers live immediately after the struct, no extra cache misses during traversal. my benchmarks show meaningful wins over std::map at 250K+ elements largely due to this cache density improvement by around 30%-40% or so.

This seems sort of messy though, and I was looking for a modern C++ alternative

I looked at std::span but it still needs a separate allocation for the pointer slots and adds 16 bytes of metadata per node. std::array requires compile-time size. std::inplace_vector (C++23) also needs a compile-time max.

Is the flexible array member still the only real tool for this pattern in modern C++? Is there something cleaner I'm missing, or is this just a gap in the language?

Using C++23, GCC, single-threaded for now.

reddit.com

Why do people do or not do ‘using namespace std;’??

This is a general question i really just dont have a good answer for and something ive wondered a long time. Does using namespace std conflict with libraries im just conveniently not using? Or is it a personal choice? The syntactic aid it lends seems too good not to use, so why not?

reddit.com
u/veilofmiah — 2 days ago

Beginner Programmer in C++

I made a small Snake TUI game, to test my skill with out using AI. and also if anyone want to help or at least want to learn how to work with someone in github you are very welcome to contribute.

public repo: https://github.com/Cee-Ry/SnakeGame-TUI

u/Cee-Rye — 1 day ago

Advice for my C# Based Fuzzer?

I mainly focus on C++/C Development, but some months ago I just made my own little C# fuzzer,

Would like to get some recommendations on how to improve my work especially because I'm actually not the best programmer when it comes to structure or anything related, because I'm still visiting high school.

https://github.com/KernelPhantom-010/DaFuzz-GUI--and-Console-program-Fuzzer

Based on the fact that I won't be able to set it to open source because I won't be home for 3 months, I'm sorry for this dry showcase, but for those who actually test it or review my source code, thanks for any improvement ideas!!

u/Empty_Commercial_380 — 18 hours ago

First project after 6months of study, please roast.

I started learning c++ 6 months ago. It hasn't been easy but I persevered. So I decided to practice by building a react native module because I use react native for work.
It is a nitro module written mostly in c++, please roast and give your critique for improvements.
I'm not so sure I followed all the best practice for c++, your feedback will help.

https://github.com/ifeoluwak/react-native-nitro-cache

reddit.com
u/ifeoluwak — 2 days ago

What is the point of classes having private members?

I just started learning about classes but I don't understand this detail. If member of a class are private, how can they be used? I read this phrase on the learncpp site but I don't get the meaning:  "Private members are members of a class type that can only be accessed by other members of the same class."

What does this mean?

reddit.com
u/Eva_addict — 2 days ago

ASAN is going to deadlock state

When I try to run with -fsanitize=address it is infinitely looping and when I do debugging using lldb. This is what I got.

* thread #1, stop reason = signal SIGSTOP   * frame #0: 0x0000000182194c88 libsystem_kernel.dylib`swtch_pri + 8     frame #1: 0x00000001821d5c28 libsystem_pthread.dylib`cthread_yield + 36     frame #2: 0x000000010062de1c libclang_rt.asan_osx_dynamic.dylib`__sanitizer::internal_sched_yield() + 16     frame #3: 0x0000000100630d24 libclang_rt.asan_osx_dynamic.dylib`__sanitizer::StaticSpinMutex::LockSlow() + 64     frame #4: 0x000000010065e9cc libclang_rt.asan_osx_dynamic.dylib`__asan_init.cold.1 + 68     frame #5: 0x000000010061efa8 libclang_rt.asan_osx_dynamic.dylib`__asan::AsanInitFromRtl() + 40     frame #6: 0x0000000100615a70 libclang_rt.asan_osx_dynamic.dylib`__sanitizer_mz_malloc + 36     frame #7: 0x0000000182005178 libsystem_malloc.dylib`_malloc_zone_malloc_instrumented_or_legacy + 152     frame #8: 0x0000000181fe9678 libsystem_malloc.dylib`_malloc_type_malloc_outlined + 96     frame #9: 0x0000000181ea3d94 libsystem_blocks.dylib`_Block_copy + 84     frame #10: 0x0000000242a128c8 Dyld`dyld_shared_cache_iterate_text_swift + 28     frame #11: 0x0000000100632d60 libclang_rt.asan_osx_dynamic.dylib`__sanitizer::get_dyld_hdr() + 236     frame #12: 0x0000000100633110 libclang_rt.asan_osx_dynamic.dylib`__sanitizer::MemoryMappingLayout::Next(__sanitizer::MemoryMappedSegment*) + 148     frame #13: 0x0000000100631a38 libclang_rt.asan_osx_dynamic.dylib`__sanitizer::MemoryRangeIsAvailable(unsigned long, unsigned long) + 172     frame #14: 0x000000010061f9b8 libclang_rt.asan_osx_dynamic.dylib`__asan::InitializeShadowMemory() + 104     frame #15: 0x000000010065ead4 libclang_rt.asan_osx_dynamic.dylib`__asan::AsanInitInternal() (.cold.1) + 260     frame #16: 0x000000010061efe8 libclang_rt.asan_osx_dynamic.dylib`__asan::AsanInitInternal() + 52     frame #17: 0x000000010065e9b0 libclang_rt.asan_osx_dynamic.dylib`__asan_init.cold.1 + 40     frame #18: 0x000000010061efa8 libclang_rt.asan_osx_dynamic.dylib`__asan::AsanInitFromRtl() + 40     frame #19: 0x00000001006151d0 libclang_rt.asan_osx_dynamic.dylib`wrap_malloc_default_zone + 16     frame #20: 0x0000000181fd94ac libsystem_malloc.dylib`__malloc_init + 1524     frame #21: 0x0000000191ff5328 libSystem.B.dylib`libSystem_initializer + 204     frame #22: 0x0000000181e48e30 dyld`invocation function for block in dyld4::Loader::findAndRunAllInitializers(dyld4::RuntimeState&) const::$_0::operator()() const + 180     frame #23: 0x0000000181e54114 dyld`invocation function for block in dyld3::MachOAnalyzer::forEachInitializer(Diagnostics&, dyld3::MachOAnalyzer::VMAddrConverter const&, void (unsigned int) block_pointer, void const*) const + 320     frame #24: 0x0000000181e8a860 dyld`invocation function for block in mach_o::UnsafeHeader::forEachSection(void (mach_o::UnsafeHeader::SectionInfo const&, bool&) block_pointer) const + 312     frame #25: 0x0000000181e87394 dyld`mach_o::UnsafeHeader::forEachLoadCommand(void (load_command const*, bool&) block_pointer) const + 208     frame #26: 0x0000000181e88c3c dyld`mach_o::UnsafeHeader::forEachSection(void (mach_o::UnsafeHeader::SectionInfo const&, bool&) block_pointer) const + 124     frame #27: 0x0000000181e53c08 dyld`dyld3::MachOAnalyzer::forEachInitializer(Diagnostics&, dyld3::MachOAnalyzer::VMAddrConverter const&, void (unsigned int) block_pointer, void const*) const + 516     frame #28: 0x0000000181e437d4 dyld`dyld4::Loader::findAndRunAllInitializers(dyld4::RuntimeState&) const + 528     frame #29: 0x0000000181e6cfb8 dyld`dyld4::PrebuiltLoader::runInitializers(dyld4::RuntimeState&) const + 44     frame #30: 0x0000000181e10850 dyld`dyld4::APIs::runAllInitializersForMain() + 100     frame #31: 0x0000000181e1d390 dyld`dyld4::prepare(dyld4::APIs&, mach_o::UnsafeHeader const*) + 3880     frame #32: 0x0000000181e1c44c dyld`dyld4::start(dyld4::KernelArgs*, void*, void*, unsigned long long)::$_1::operator()() const + 320     frame #33: 0x0000000181e1bda8 dyld`start + 6904

reddit.com
u/0x6461726B — 19 hours ago

Is there a runtime performance difference between incremental and unity builds?

On one hand, a unity build would expose the implementation of every function, allowing for better optimization. On the other hand, things that were previously local to one translation unit would now be exposed across the project, possibly harming the compiler's ability to reason about its usage.

reddit.com
u/celestabesta — 17 hours ago

Address sanitiser is not working

Hi guys I have written a double free code in my main.cpp

int main() {
    int* p = (int*)malloc(sizeof(int));
    free(p);
    free(p);
    return 0;
}

And compiling it with

clang++ -std=c++20 -O0 -I./vega -I/opt/homebrew/include -fsanitize=address -fno-omit-frame-pointer -c main.cpp -o build/main.o 

                                                                                                                       clang++ build/bechmarks.o build/main.o build/tests.o -L/opt/homebrew/lib -lpthread -fsanitize=address -o program

And running ./program. I am seeing nothing in the output.

reddit.com
u/0x6461726B — 2 days ago

Hey guys i find it difficult to work with logic

I'm a c++ programmer it's been 45 days of me practicing this language and i even solved a few easy hacker-rank questions(14 questions) and leet-code questions(2 leet codes palindrome number and dividing two integers) .

I realised what my problem is, i understand the question but i can't work around the logic

Sometimes when i chatgpt the problem i understand the solution of the code very easily but i just can't work around it in my head.

Any help appreciated.

reddit.com
u/OkSelection1372 — 2 days ago
▲ 14 r/cpp_questions+1 crossposts

Why doe the velocity not work as an integer

int vel_y = 5;
float gravity = 0.3f;

// MAIN LOOP
while(!WindowShouldClose()){
        BeginDrawing(); // Setup canvas
        ClearBackground((Color) {0, 0, 0, 255});

        // Draw Ball
        DrawCircle(ball_x, ball_y, ball_radius, (Color){255, 255, 255, 255});

        // Physics
        vel_y += gravity;
        ball_y += vel_y;

        if (ball_y &gt;= (screen_h - ball_radius)) {
                ball_y = screen_h - ball_radius;  
                vel_y = -vel_y * 0.8f;
        }
}

Why is int vel_y = 5; being an integer causing the ball not bounce
but when it becomes a float it works why?

This is what it looks like after than before

https://imgur.com/a/oxR07xf

u/TheEyebal — 2 days ago
🔥 Hot ▲ 62 r/cpp_questions

What are some “fun” things to code in c++?

C++ is a fun language, but I find myself struggling to come up with things to code. I feel like c++ is more so for systems. Any Ideas on what I could code? I feel very stuck. I coded a Gacha Banner System but besides that nothing really pops out.

reddit.com
u/Prior-Scratch4003 — 3 days ago

[RevShare] ¿Quieres ser parte de Bed Teddy Studio?

Este proyecto se basa en juntar un grupo de personas talentosas, disciplinadas y responsables que crean en mis ideas para hacerlas realidad.

Actualmente estoy desarrollando un juego, para resumirlo en un pequeño texto es un Simulador de vida y economía 2D (con esencia 2.5D) centrado en la libertad total, la movilidad social y la supervivencia. Todo corre bajo un motor propio (Bed Teddy Engine) programado desde cero en C++20, diseñado para ser ultra-eficiente y correr en hardware de hace 20 años.

El modelo de trabajo es RevShare (reparto de ingresos por porcentajes), distribuidos de la siguiente manera:

Yo, Bed Teddy (Líder/Motor): 32%

Puestos libres:

2 Programadores C++ : 15% c/u

3 Pixel Artists 16x16 : 10% c/u

Diseñador de Audio (Trap/ASMR): 7%

2 Testers: 0.5% c/u

¿Que busco?

Programadores: que tengan experiencia con SDL2 entre otras librerías.

Artistas: Que dominen el estilo 16-bits.

Disciplina: No pido 40 horas semanales, solo pido que lo que se acuerde, se cumpla en un lapso de tiempo razonable :)).

El juego ya tiene una base sólida.

REQUISITOS:

Hablar español

Dominar OOP junto librerías como SDL2 en C++

Tener así sea solo un ejemplo que me puedas mostrar

Si eres Venezolano, sería bueno, pero igualmente puedes entrar al equipo sin la necesidad de ser venezolano 😅

Escribe al privado si te interesa

reddit.com
u/Bed_Teddy — 2 days ago

Why a lmdb replacement hasn't happened in c++?

The latest wrapper release is 4 years old, the one on awesome cpp is 11 years old.

There is lmdb replacement by a russian dude, but he doesn’t open source tests for weird ass reasons and deliberetely ships a 40k loc source so people don't fork it.

Rocksdb exists but is huge, and is very slow to compile, and doesn’t really compare to btree solutions if stuff I read is true.

I don’t really get it, parallel data read/write is such an important thing, why we don’t have anything for it?

reddit.com
u/TheRavagerSw — 3 days ago

Immutability or a kind of "reverse shallow const"

I'm looking at writing an immutability wrapper.

Context

Most of the languages I know have immutable strings, which is distinct from C++ const strings, e.g C# like this:

string s = "hello";
s = "hello world" // allowed - the string reference was reassigned to a different string, the original string was not mutated
s = s + '!'; //allowed - a allocates a new string through concatenation
s[0] = 'H'; //won't compile
s = 'H' + s.SubString(1); //allowed - allocates twice, but allowed.

(see also golang, python, js)

The reason, as far as I can tell, is that these languages default to passing most T by T*, so they build immutability into the types (when possible). In C++ we have the option of passing T by T const&amp; or T const*, so built-in immutability has been less of a priority.

Yet, immutability does buy something we don't get with const&amp; - sure, as the caller, we know the callee can't modify the string. But as the callee, just because we wrote std::string const&amp; in our function signature, that doesn't guarantee the string won't be modified elsewhere, whether it be async code, or just that we stored the reference and expected it to stay valid.

Question

Before I spend any time on this - is this a solved problem already?

My initial thought was that the fastest "immutability wrapper" to write would be as simple as

template&lt;typename T&gt;
using Immutable = std::shared_ptr&lt;const T&gt;;

Unfortunately...

int main() {
    auto s = std::make_shared&lt;int&gt;(2);
    Immutable&lt;int&gt; i = s;
    *s = 1;
    return *i; //returns 1;
}

same semantics as regular pointers - sure, the callee can't change it out, but they can't depend on its unchanging nature, either.

reddit.com
u/SoerenNissen — 3 days ago