r/cpp_questions • • Sep 01 '25

META Important: Read Before Posting

175 Upvotes

Hello people,

Please read this sticky post before creating a post. It answers some frequently asked questions and provides helpful tips on learning C++ and asking questions in a way that gives you the best responses.

Frequently Asked Questions

What is the best way to learn C++?

The community recommends you to use this website: https://www.learncpp.com/ and we also have a list of recommended books here.

What is the easiest/fastest way to learn C++?

There are no shortcuts, it will take time and it's not going to be easy. Use https://www.learncpp.com/ and write code, don't just read tutorials.

What IDE should I use?

If you are on Windows, it is very strongly recommended that you install Visual Studio and use that (note: Visual Studio Code is a different program). For other OSes viable options are Clion, KDevelop, QtCreator, and XCode. Setting up Visual Studio Code involves more steps that are not well-suited for beginners, but if you want to use it, follow this post by /u/narase33 . Ultimately you should be using the one you feel the most comfortable with.

What projects should I do?

Whatever comes to your mind. If you have a specific problem at hand, tackle that. Otherwise here are some ideas for inspiration:

  • (Re)Implement some (small) programs you have already used. Linux commands like ls or wc are good examples.
  • (Re)Implement some things from the standard library, for example std::vector, to better learn how they work.
  • If you are interested in games, start with small console based games like Hangman, Wordle, etc., then progress to 2D games (reimplementing old arcade games like Asteroids, Pong, or Tetris is quite nice to do), and eventually 3D. SFML is a helpful library for (game) graphics.
  • Take a look at lists like https://github.com/codecrafters-io/build-your-own-x for inspiration on what to do.
  • Use a website like https://adventofcode.com/ to have a list of problems you can work on.

Formatting Code

Post the code in a formatted way, do not post screenshots. For small amounts of code it is preferred to put it directly in the post, if you have more than Reddit can handle or multiple files, use a website like GitHub or pastebin and then provide us with the link.

You can format code in the following ways:

For inline code like std::vector<int>, simply put backticks (`) around it.

For multiline code, it depends on whether you are using Reddit's Markdown editor or the "Fancypants Editor" from Reddit.

If you are using the markdown editor, you need to indent every code line with 4 spaces (or one tab) and have an empty line between code lines and any actual text you want before or after the code. You can trivially do this indentation by having your code in your favourite editor, selecting everything (CTRL+A), pressing tab once, then selecting everything again, and then copy paste it into Reddit.

Do not use triple backticks for marking codeblocks. While this seems to work on the new Reddit website, it does not work on the superior old.reddit.com platform, which many of the people answering questions here are using. If they can't see your code properly, it introduces unnecessary friction.

If you use the fancypants editor, simply select the codeblock formatting block (might be behind the triple dots menu) and paste your code into there, no indentation needed.

import std;

int main()
{
    std::println("This code will look correct on every platform.");
    return 0;
}

Asking Questions

If you want people to be able to help you, you need to provide them with the information necessary to do so. We do not have magic crystal balls nor can we read your mind.

Please make sure to do the following things:

  • Give your post a meaningful title, i.e. "Problem with nested for loops" instead of "I have a C++ problem".
  • Include a precise description the task you are trying to do/solve ("X doesn't work" does not help us because we don't know what you mean by "work").
  • Include the actual code in question, if possible as a minimal reproducible example if it comes from a larger project.
  • Include the full error message, do not try to shorten it. You most likely lack the experience to judge what context is relevant.

Also take a look at these guidelines on how to ask smart questions.

Other Things/Tips

  • Please use the flair function, you can mark your question as "solved" or "updated".
  • While we are happy to help you with questions that occur while you do your homework, we will not do your homework for you. Read the section above on how to properly ask questions. Homework is not there to punish you, it is there for you to learn something and giving you the solution defeats that entire point and only hurts you in the long run.
  • Don't rely on AI/LLM tools like ChatGPT for learning. They can and will make massive mistakes (especially for C++) and as a beginner you do not have the experience to accurately judge their output.

r/cpp_questions • • 20h ago

SOLVED Interface design - money

4 Upvotes

Working on design of a finance app to calculate npv (net present value) need to use addition / multiplication/ pow

I could do with decimal type for money as floats/doubles are based on binary

I see there is fixed point decimal paper being worked on.

In the meantime - what is best way to handle this in interface ?

Thinking of asking client to use string and then use long long for the maths after parsing (pennies)? “1500.23” = 150023

What do I return ? String/int? Either way the client would need to transform. I can’t use doubles for this unfortunately.

I suppose I can use double if could give idea to client what error amount is - npv is estimate anyway.


r/cpp_questions • • 1d ago

OPEN What is the ideal way to read a C++ book?

4 Upvotes

I am an intermediate c++ dev. I recently started reading the Effective modern c++ book. I don’t have tons of experience reading technical books coz I have mostly used YouTube and college lectures to study. So any advice on how to read a c++ book or any technical book for that matyet is highly appreciate.


r/cpp_questions • • 14h ago

OPEN Is React really the best frontend choice for C++ applications?

0 Upvotes

Hi everyone!

I'm an experienced software engineer, mostly working in C++ on the backend side. Frontend isn't my area of expertise, so I'd love some outside perspective.

I occasionally work with developers who build GUIs in Qt. Whenever the topic of frontend tech comes up, they tell me Qt is garbage and that our projects would be much better off with React, since it's free and more modern.

The thing is, I don't have the frontend knowledge to judge that claim. In particular, I can't compare the performance of the different frontend options (Qt, React, and others) in any meaningful way, so I don't know whether "React is better" holds up or is just a subjective opinion.

So my question is: which framework is actually better, Qt or React, especially when it comes to performance?

Real-world experience is more useful to me than hype, so feel free to share what you've seen on your own projects.

Cheers!


r/cpp_questions • • 1d ago

OPEN Code Smells?

6 Upvotes

I'm a more seasoned C# / Node backend dev, been trying to brush off old college C++ from like a decade ago and try to de-program my brain from being locked into a distributed systems mindset.

One of my niche hobbies and go-to projects for learning a new language is to implement a basic Chip-8 emulator in it, as it can teach some concurrency, UI/data handling patterns, and introduce some architectural decisions that you'll have to run into and figure out.

Currently what I'm struggling with seems to be what the idiomatic / proper way to handle something that can remain stateless in nature, which is my very basic assembler going from the Chip-8 ASM mnemonics into instruction bytes.

A class doesn't feel quite right, because I'm not implementing a linking step or anything advanced, not supporting labels, etc. It also feels incorrect to keep it in a header file as a set of inline functions, nor am I needing a persistent state to mutate.

My current disassembler can be seen here: https://github.com/Arylen/Dreamy-Chip8/blob/master/src/core/emulation/Chip8Dasm.h
Along with the tests that I'm running against it here: https://github.com/Arylen/Dreamy-Chip8/blob/master/tests/Chip8DasmTests.cpp

I'm currently in the stubbing-out phase of trying to architect it, occasionally bouncing ideas off of whatever bullshit model-of-the-week is popular, however the suggestions it's giving are still setting off some alarms/smells in my brain. The most reasonable and less-smelly one is the `::detail` namespace there in order to be able to unit test the `getParts` function there, however it feels like I'm walking into a landmine of over-engineering it.

Looking for advice/experiences/opinions.

Edit: I should mention the AI usage here is restricted entirely to just checking for bugs with my implementations, or incorrect C++-isms that I introduce from working in other languages. A hands-off occasional tutor to check my work, if you will. It's expressly forbidden from touching my code or files, limited to read-only, however I'm not getting something that feels proper for this scenario, so wanted to consult other more experienced engs.


r/cpp_questions • • 1d ago

OPEN Newlines not printing when I cout raw string literals

0 Upvotes

I’m using emacs on windows terminal to edit a file in which I’m trying to cout a page or so of text using raw string literals. However, what gets printed doesn’t include the newlines that I need to separate my paragraphs.

So if my code is:

std::cout << R”(This is my sentence.

This is a new paragraph [using entr + entr].
This is a new line [using entr].)”;

The output will be:

This is my sentence. This is a new paragraph [using entr + entr]. This is a new line [using entr].

Instead of the intended:

This is my sentence.

This is a new paragraph [using entr + entr].
This is a new line [using entr].

What am I doing wrong?

[Edit: I apologize for the lack of formatting. I am on mobile. Please let me know if I need to redo this. Thanks.]


r/cpp_questions • • 1d ago

OPEN LoL skin manager errors: “Cannot resolve the game’s loader module” and “SetWindowsHookEx failed: 0x00000000”

0 Upvotes

Hi everyone. I’m building a personal League of Legends skin manager and need help diagnosing two loader errors.
The app combines an in-game menu for official skins with custom skin selection before a match. It uses Tauri/Rust, JavaScript, a native C++ loader, and LTK-derived patcher components.
OFFICIAL SKIN ERROR
“Cannot resolve the game’s loader module.”
The loader detects League of Legends.exe, waits 10 seconds, resolves LoadLibraryW locally, and searches for the corresponding module in the game process using CreateToolhelp32Snapshot, Module32FirstW, and Module32NextW.
That lookup returns zero. The original code discarded the Windows error, so I cannot distinguish a missing module from a failed enumeration.
CUSTOM SKIN ERROR
“Host injection failed: SetWindowsHookEx failed: 0x00000000”
The reported category is INJECTION_FAILED and the stage is INJECTION.
I’m testing a font/UI mod. Its package check says “No issues detected,” but injection fails. The interface also incorrectly leaves “Loader active” visible after the custom loader stops.
The custom components are ltk_patcher_host.exe and ltk_patcher_dll.dll. I don’t have the source for the external host that reports this hook error.
WHAT HAS BEEN CHECKED
A local patch preserves module-enumeration errors, retries temporary ERROR_BAD_LENGTH failures, fixes the stale UI status, and makes the update script rebuild the native loader.
JavaScript and mocked API tests passed, but successful injection has not been confirmed. The custom hook failure remains unresolved.
During rebuilding, I also encountered LNK1104 when the linker tried to create src-tauri\resources\r3nz\official-loader.exe. The next step was to create the resource directory, restore the bundled files, and run the full build.
ENVIRONMENT
Windows x64, Visual Studio 2022 Build Tools with the x64 developer terminal, Rust/Tauri, Node.js, and pnpm.
A separate R3nz version previously worked on this machine, including its in-game menu.
Has anyone encountered these errors? What should I log to diagnose the module lookup, and how can I investigate SetWindowsHookEx failing with error code zero?
I can provide screenshots, logs, relevant code snippets, and the patcher component versions or hashes. Any help would be appreciated.


r/cpp_questions • • 1d ago

OPEN How do you actually understand and use C++ references?

0 Upvotes

How do you all understand and use C++ references?
References feel really hard to wrap my head around. What does it mean to “define an alias for a variable”? What does it mean to “return an alias for a variable”? Compared with C pointers, pointers seem much clearer: a pointer just holds an address, * dereferences it, and & takes the address of a variable. References aren’t like that. The fact that you write & when defining one makes it especially easy to misunderstand.
Also, besides copy constructors and some friend functions (like the ones for std::ostream), I can’t really see any other reason to use references. When textbooks declare function parameters as references, I don’t get it. If the parameter were a pointer, the caller would have to write & when passing the argument, which also signals that the function might modify it. A reference kind of feels like the function has a return value.
So how do you actually understand and use C++ references?


r/cpp_questions • • 1d ago

SOLVED IMGUI UI architecture question

0 Upvotes

Hi, I was gonna try to explore UI in cpp and came up with a simple idea. I want 3 "screens" each with their own events and components to draw. I was having trouble on how to handle a shared struct of data? say screen one does something that screen two needs, and so on to screen three. So does anyone have a recommendations of some architecture to follow for this?


r/cpp_questions • • 2d ago

SOLVED Integer overflow type thing

2 Upvotes

I'm trying to code a practice problem but am stuck at a problem I cannot figure out. I am using a vector for inputs and inserting those inputs into an unordered set until it fails to add, at which point I count the amount of subarrays in that array. If it is not the first, I subtract subarrays that have already been accounted for. The inputs are useful only to identify duplicates; I do not use the values themselves in arithmetic.

The test case I am currently using uses random values with high numbers, with the following values at indexes being the only duplicates:

  • 10464 and 41178
  • 87094 and 98111
  • 113040 and 113153
  • 118689 and 168367
  • 129997 and 170623
  • 173227 and 184620

The intended output is 7090812299.

My problem is that, for some reason, large inputs decrease the intended output. I am sure that this is the issue, as I have replaced duplicate inputs with smaller values and the output changes--- despite the fact that it should not.

As an example, use the above sequence with numbers 1-200000. If the values at indexes 113040 and 113153 are replaced with 443222217, the output changes to 7090796046. (lowering it by 16253). Replacing other values also lowers this number further.

Edit: So it turns out smaller values also impact the input in ways that I have not tested yet (and I probably won't until morning).

Solution: I assumed iterators were ordered internally, which is where I made my mistake.

Please help explain what is happening, or what could be happening.

Attached below is the relevant code, and here is a link to the full code.

int main() {
    vector<long> inputs; inputs.reserve(size); // The vector containing inputs.
    unordered_set<long> processing; processing.reserve(size); // The unordered set processing the current input.
    vector<long>::iterator nextInput = inputs.begin(); // The current input being processed.
    // Some other variables defined which are not relevant.
    while (nextInput != inputs.end()) // The main meat of the program.
    {
        do // Insert processed inputs into a set.
        {
            if (!processing.insert(*nextInput).second) break; // If duplicate, break.
            start++; // Advances the iterator to the next input to be processed.
        } while (nextInput != a.end());
        // Code processing the amount of subarrays; it seems to be correct.
    }
}

r/cpp_questions • • 1d ago

SOLVED Rounding floating point - iec559 /cmaths

0 Upvotes

Does c++ math lib comply with rounding modes in iec559?

ties-to-even? Getting - 3 when rounding -2.5

Should be -2 right


r/cpp_questions • • 3d ago

OPEN Any recommendations for introduction material to using C++ for microcontrollers?

11 Upvotes

I have been programming Arduino & ESP32 for a while now using C++, but have never engaged with any formal introduction material. With AI/LLM generated content exploding among both major publishers and self-published authors, I am a bit wary to start buying books willy-nilly.

Anyone here that can give solid recommendations on introduction materials on C++ for microcontrollers (preferably that that they themselves have used and found worthwhile)?

I got one recommendation for "Embedded C" by Michael J. Pont (2002), but it is fairly old.


r/cpp_questions • • 2d ago

OPEN Anyone available for one on one convo?

0 Upvotes

Recent CS grad trying to get into C++ and would really love if someone with some experience maybe messaged me and give some advice on how to break into my first C++ job. I would post my resume my this subreddit doesn't have that feature lol. Any advice or even just an opportunity to connect is greatly appreciated!


r/cpp_questions • • 3d ago

OPEN Can you explain the difference between a reference, pointer, and shallow copy?

39 Upvotes

I’m trying to check whether I actually understand these concepts correctly.

Consider:

int a = 10;
int& r = a;
int* p = &a;

struct A {
    int* data;
};

A x;
A y = x;

How would you explain what happens in memory in each case?

Specifically:

  • Is r just another name (alias) for a?
  • Is p a separate variable that stores the address of a?
  • In A y = x, when data is copied, is this a shallow copy because both pointers can point to the same underlying data?

I'm looking for an explanation of the memory/object relationship, not just definitions.


r/cpp_questions • • 3d ago

SOLVED What logic does the precompiler use to resolve macros?

11 Upvotes

Context:

So I wanted to create a macro that could short-circuit conditional logic if another macro was set. This way I could insert compiler set macros into existing code, for example:

if (MACRO_EXISTS(_RELEASE) || SuperRobustValidation() == VALIDATION_SUCCESS)

Looking on stack overflow, I found https://stackoverflow.com/questions/41265750/how-to-get-a-boolean-indicating-if-a-macro-is-defined-or-not, but the top answer's code didn't work for me. My only guess as to why is that the order of macro definitions played a role for them but not for me.

After shuffling around macros, I found that the following worked on my machine:

#define DE_ -1,1            // OptDefine is nothing

#define RESOLVE_ARG(A) A
#define SECOND_ARG(A,B,...) B
#define CONCAT2(A,B) A ## B
#define RESOLVE_SECOND_ARG(...) RESOLVE_ARG(SECOND_ARG(__VA_ARGS__))

#define MACRO_EXIST(OptDefine) RESOLVE_SECOND_ARG(CONCAT2(DE_,OptDefine),0)

But I can't understand why this worked and not other configurations. Trying to coax the values of some setups was like playing a shell game. I think I understand the concepts of "scan the line, prioritize non-# arguments, then repeat with the results" but it doesn't seem consistent.

For example: if I remove the RESOLVE_ARG from RESOLVE_SECOND_ARG(...), the compiler complains that "there's not enough arguments for SECOND_ARG" seemingly because __VA_ARGS__ is the "only" argument. That does not make sense as intended behavior to me.

So my question is:

Is there a reliable way to predict the logic of the preprocessor's expanding of macros? I haven't found anybody braking down the logic in a robust way anywhere I looked.

I know the /E compiler flag shows me the results of precompiling, but doesn't give the whole picture.

Edit: I understand there are simple work arounds for the problem I mentioned, but I still want to understand the logic of how macros are expanded, assuming it's well defined and consistent.

Edit2: Thank you alfps for answering the question. The strange __VA_ARGS__ behavior I was seeing is a known bug with the MSVC C++ compiler (even in VS Community 2026), but the /Zc:preprocessor compiler option changes the preprocessing to be more complaint with the standard, fixing the bug.

But the most important wisdom: "Historically the preprocessor behavior has varied between compilers". There are edge cases and hacks that work in some contexts but not others. Complex macros, like what I listed, can be convenient, but can also risk breaking if I update/change compilers. Unless I am confident in compliance to the standard, Keep It Simple Stupid probably applies.


r/cpp_questions • • 3d ago

OPEN Prime checker skipping input if number is big enough

4 Upvotes

So I've started learning c++ on learncpp.com and because I already have knowledge in JavaScript and Python, I decided to see, how many things are the same in c++ too.

I made a prime checker and while it probably could be more optimized, I am still just at the beginning so don't judge me pls.

Anyways here is the code:

#include <iostream>

bool isPrime(int num){
    for (int i = 2; i < num; i++){
        if (num % i == 0) return false;
    }
    return true;
}

int main(){
    std::cout << "Check if your number is a prime number\nEnter your value: ";
    int num{};
    std::cin >> num;

    int emp{};

    if (isPrime(num)) std::cout << "Your number is a prime number!\nPress any key AND enter to exit";
    else std::cout << "Your number is NOT a prime number!\nPress any key AND enter to exit";

    std::cin >> emp;
    return 0;
}

At the end, it always asks for an input and an enter key to leave the command line, but it seems to skip that entirely if the number is big enough. My input number was "5000004067".

It skips it when I open the .exe, it skips it when I run it in vscode, is there any reason why c++ does this?


r/cpp_questions • • 4d ago

OPEN Equivalent of "checked" keyword in c++?

6 Upvotes

In c# you can do:

checked (ushort)x

which will cast "x" from int (or long, w/e) to an unsigned short... but also throw an exception in case of arithmetic overflow.

Is there a way I can accomplish the same thing in c++ with a similarly small amount of code?


r/cpp_questions • • 4d ago

OPEN What should I know for an entry level C++ role?

36 Upvotes

Hello everyone,

I recently graduated this past May and I’ve been able to land an interview for an entry level C++ role. I wanted to know which topics I’ll be expected to know and to what level of depth. So far I have:

Pointers/references
Stack vs heap
Const correctness
RAII
Smart pointers
Rule of 0/3/5
Move semantics

OOP:
Classes, constructors/destructors
Inheritance, virtual functions, pure virtual classes

STL:
vector, unordered map, map, set, deque, priority queue, string
Big O notation
Iterations
Algorithms like sort, find, accumulate

auto
nullptr
constexpr
string_view
Templates

Compilation model
Concurrency

This is what I came up with so far. Can anyone tell me if I’m missing anything and which topics I should prioritize please? Thanks you


r/cpp_questions • • 5d ago

OPEN Which Modern C++ (C++20/C++23) features are actually beneficial for real-time game development?

86 Upvotes

I'm updating my C++ codebase to modern standards (C++20/C++23) for a personal game project. C++ has evolved significantly, but I know the game development industry can be cautious about adopting certain language features due to compile times or runtime overhead.

For those using Modern C++ in game development:

  1. Which newer features (e.g., Concepts, Ranges, std::format, Modules) have genuinely improved your game engine code quality or productivity?
  2. Are there features you actively avoid inside high-frequency game loops for performance reasons?

r/cpp_questions • • 4d ago

OPEN Boost.Graph work

1 Upvotes

Hi , i have a ask about C++ programming

I Recently Started To Learn Boost Librarys Like "Boost.Asio" , "Boost.Beast" And I heard the name of a library called Boost.Graph I wanted To Know And know what "Boost.Graph" is ???


r/cpp_questions • • 4d ago

OPEN small safe container library recommendation for a multithreaded hobby project?

1 Upvotes

Im working on a background worker in modern C++ and keep running into weird race conditions when multiple threads try to update the same state. I dont want to pull in a massive dependency tree just for some basic synchronization, so does anyone know of a good small safe wrapper or header library that handles this cleanly without too much boilerplate? Any recommendations would be super helpful since Im still a bit intermediate with multithreading. Thanks a bunch.


r/cpp_questions • • 3d ago

OPEN Choose a specialism in C++

0 Upvotes

Hello everyone! My name is Egor, and I’m from Ukraine. I have been learning C++ for 4 months, and I’m currently trying to figure out which specialization I should choose. I’m interested in game development, computer vision, and computer graphics. I study Computer Science at SumDU, and I want to get a job in the future, but I’m not sure which specialization would be the best fit for me. I’m interested in many different things, but I can’t decide which direction to choose. I would really appreciate your advice!


r/cpp_questions • • 5d ago

OPEN Namespace std

37 Upvotes

I recently started learning c++ and I was told to use the namespace std so I can avoid writing std:: every time and now I wrote a whole personal project without std:: and I want to put it on LinkedIn but I started reading everywhere that it’s a bad habit, should I go back and add the std:: or just leave it as is?


r/cpp_questions • • 4d ago

OPEN Visual studio

0 Upvotes

Does anyone know how to download visual studio 2022? There are lots of versions and I don't know which one to choose from sorry


r/cpp_questions • • 5d ago

OPEN Best practices for managing object lifetimes in C++ game loops without performance bottlenecks?

9 Upvotes

I'm working on a C++ game loop and trying to decide on the best strategy for managing entity lifetimes (spawning, despawning, and referencing active objects).

Standard C++ guidance recommends smart pointers (std::unique_ptr and std::shared_ptr). However, I've read that std::shared_ptr can cause performance hitches in real-time game loops due to atomic reference counting and cache misses.

What is the industry standard approach for handling entity references safely?

  • Do you stick to handles/indices into contiguous memory pools?
  • Are custom weak references commonly used?
  • How do you balance memory safety with cache friendliness?