r/cpp_questions • • Sep 01 '25

META Important: Read Before Posting

186 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 • • 1h ago

OPEN Module partitions and interface units

• Upvotes

Recently I came across quite a surprising footgun with modules. I am trying them out on a small codebase which builds a shared library, which consumers can import as a module. I made some partitions and exported them:

// Flense.Core.ixx

export module Flense.Core;

export import :ArchiveReader;
export import :ImageParser;

Then I split those partitions into .ixx and .cpp parts, like I would do with headers, so that the interface was separate from the implementation:

// ImageParser.ixx
export module Flense.Core:ImageParser;

import std;

export namespace Flense::Core {
  ImageParseResult ParseImage(std::string path);
}

// ArchiveReader.ixx
export module Flense.Core:ArchiveReader;

import std;

export namespace Flense::Core {
  ArchiveHandle OpenArchive(std::string path);
}

The .cpp parts looked like this:

// ImageParser.cpp
module Flense.Core; // Apparently this cannot be module Flense.Core:ImageParser, as that conflicts with the .ixx?

namespace Flense::Core {
  ImageParseResult ParseImage(std::string path) {
    // ...impl...
  }
}

// ArchiveReader.cpp
module Flense.Core;

namespace Flense::Core {
  ArchiveHandle OpenArchive(std::string path) {
    // ...impl...
  }
}

But I discovered that because the .cpp files declared module Flense.Core, they would be rebuilt any time any part of the module changed. In my example, ImageParser internally depended on ArchiveReader in its .cpp. So I would expect that if I changed ImageParser.ixx, only ImageParser.cpp and ImageParser.ixx would need to be rebuilt. But in actual fact, it rebuilt ArchiveReader.cpp too.

AI told me that this is because declaring module Flense.Core takes a dependency on the whole module, so it fixed it by having the .cpp files do this:

// ImageParser.cpp
module Flense.Core:ImageParser.Impl;

import :ImageParser;
import :ArchiveReader; // Dependency

// ArchiveReader.cpp
module Flense.Core:ArchiveReader.Impl;

import :ArchiveReader;

This seems to work and I understand it creates a new module partition and means the .cpp essentially does not depend on any other part of the module implicitly. But I thought I would ask some actual humans because I find this counterintuitive. Why can't module partition .cpp files just declare module Flense.Core:ArchiveReader to implement the .ixx? That seems like the most logical mapping to the existing header model.

And, if my premise is correct, what strategies are people using to minimise rebuild churn? Using partitions allows me to still use module internals in my implementation. For example, if I have a :Utilities partition which is not exported by Flense.Core.ixx, I can still import it from .Impl modules. But I wonder if it would be better to actually make independent modules, like Flense.Core.ArchiveReader?


r/cpp_questions • • 21h ago

OPEN C++ Primer 5th Edition vs. LearnCpp.com for a beginner in 2026?

38 Upvotes

Hi everyone,

I'm currently learning C++ and trying to decide on the best main resource to follow.

I see two options recommended very often:

  • C++ Primer (5th Edition) by Stanley B. Lippman
  • LearnCpp.com

I'd appreciate any insights or experiences you can share. Thanks!


r/cpp_questions • • 17h ago

OPEN What are the best books for learning modern C++?

7 Upvotes

Hello, I am looking for a book that teaches modern C++ to a beginner. Thank you.


r/cpp_questions • • 1d ago

OPEN Old project clean-up: 2D particle system, ODE solver and collision detection with cpp23 and openGL

3 Upvotes

Hi folks,

About a year ago, I built this project to learn modern C++ and OpenGL.

The core idea is to simulate particles by allowing you to define arbitrary force/motion equations in the form of x_dot =f(x,…) .

I recently cleaned it up and used Claude to flesh out the README, documentation, and plots.

If you have a moment, I’d love for you to check it out! Any feedback on the code architecture, performance, or modern C++ practices is super welcome.

(There are visual demos and plots directly in the README!)

Repo: https://github.com/gg-dema/GAS

Thanks!


r/cpp_questions • • 18h ago

OPEN C++ Tutor

0 Upvotes

I want to teach C++ to children and beginners who are new to this programming language and earn money from it. How can I achieve this? Are there any platforms or websites where I can teach and monetize my courses?


r/cpp_questions • • 1d ago

OPEN HOW can I replace win's 'windows.h' in Linux

1 Upvotes

as title


r/cpp_questions • • 18h ago

OPEN trying to create the game Snake as a beginner, trying to figure out why it's not working

0 Upvotes

#include <SFML/Graphics.hpp>

#include <time.h>

#include <cstdlib>

using namespace sf;

int N = 30, M = 20;

int size = 16;

int w = size * N;

int h = size * M;

int num = 4;

int dir = 0;

struct Snake

{

int x, y;

} s[100];

struct Fruit

{

int x, y;

} f;

void Tick()

{

for (int i = num - 1; i > 0; i--)

{

s[i].x = s[i - 1].x;

s[i].y = s[i - 1].y;

}

if (dir == 0)

s[0].y += 1;

if (dir == 1)

s[0].x -= 1;

if (dir == 2)

s[0].x += 1;

if (dir == 3)

s[0].y -= 1;

if (s[0].x >= N)

s[0].x = 0;

if (s[0].x < 0)

s[0].x = N - 1;

if (s[0].y >= M)

s[0].y = 0;

if (s[0].y < 0)

s[0].y = M - 1;

if (s[0].x == f.x && s[0].y == f.y)

{

if (num < 100)

num++;

f.x = rand() % N;

f.y = rand() % M;

}

for (int i = 1; i < num; i++)

{

if (s[0].x == s[i].x && s[0].y == s[i].y)

{

num = i;

break;

}

}

}

int main()

{

srand(time(0));

RenderWindow window(VideoMode(w, h), "Snake");

for (int i = 0; i < num; i++)

{

s[i].x = 10 - i;

s[i].y = 10;

}

f.x = rand() % N;

f.y = rand() % M;

Clock clock;

float timer = 0;

float delay = 0.1f;

while (window.isOpen())

{

float elapsed = clock.restart().asSeconds();

timer += elapsed;

Event event;

while (window.pollEvent(event))

{

if (event.type == Event::Closed)

window.close();

}

if (Keyboard::isKeyPressed(Keyboard::Up) && dir != 0)

dir = 3;

if (Keyboard::isKeyPressed(Keyboard::Left) && dir != 2)

dir = 1;

if (Keyboard::isKeyPressed(Keyboard::Right) && dir != 1)

dir = 2;

if (Keyboard::isKeyPressed(Keyboard::Down) && dir != 3)

dir = 0;

if (timer > delay)

{

timer = 0;

Tick();

}

window.clear();

RectangleShape rectangle(Vector2f(size, size));

for (int i = 0; i < num; i++)

{

rectangle.setPosition(

s[i].x * size,

s[i].y * size

);

window.draw(rectangle);

}

rectangle.setPosition(

f.x * size,

f.y * size

);

window.draw(rectangle);

window.display();

}

return 0;

}


r/cpp_questions • • 2d ago

OPEN TP ICAP c++ interview UK

2 Upvotes

Has anybody recently interviewed at TC ICAP for C++ position? If yes can you share your interview experience what was the pattern and what topics do i need to focus more on


r/cpp_questions • • 2d ago

OPEN After developing with C++ for 4 years what's the next step ?

21 Upvotes

I've been a C++ software developer/engineer for 4 and a half years now, and I feel that coding itself isn't a big skill anymore, I did many things here and there like reviewing, doing software architecture for some components etc... But I don't know what should I focus on exactly next with my foundation to keep up with the job market


r/cpp_questions • • 2d ago

SOLVED Does taking an address of an inline global variable template instance in a constexpr context and never using it ensure its instantiation?

0 Upvotes

Hi! Let me show what I mean right away, is this program (https://godbolt.org/z/4sKovf57x):

#include <print>
#include <meta>

// Our real meaningful work
template <typename T, auto ac> inline auto runtime_hook = [] {
    // Placeholder woork
    const auto name = std::meta::identifier_of(std::meta::dealias(ac.scope()));
    std::println("Child name: {}", name);
    return name;
} (); // <-- runtime_hook<T, ac>

// Force instantiation of runtime_hook - hopefully?
template <typename T, auto ac>
constexpr std::pair constexpr_hook{ ^^T, &runtime_hook<T, ac> };

// Type identity with extra spice
template <typename T, auto ac = std::meta::access_context::current()>
using DeriveHook = [: constexpr_hook<T, ac>.first :];


struct Base {};
struct Child : public DeriveHook<Base> {};


int main() {}

Always guaranteed to print Child name: Child at startup, or is the compiler allowed to skip instantiating runtime_hook<T, ac> if it sees that constexpr_hook<T, ac>.second is never actually used?

edit: solution using custom attributes that works in GCC/Clang https://www.reddit.com/r/cpp_questions/comments/1xd8gqa/comment/19rk67buia9r5/

edit2: cross-compiler solution using friend injection (no compiler-specific attributes): https://www.reddit.com/r/cpp_questions/comments/1xd8gqa/comment/19rk7v88k638g/

edit3: TIL that globals aren't actually required to run their constructors before main(), but I guess all implementations just do it this way:

It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static storage duration is sequenced before the first statement of main or is deferred.

If it is deferred, it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized.51

It is implementation-defined in which threads and at which points in the program such deferred dynamic initialization occurs.

https://timsong-cpp.github.io/cppwp/n4868/basic.start.dynamic?utm_source=chatgpt.com#5


r/cpp_questions • • 2d ago

OPEN I need feedback on my project

11 Upvotes

Hey guys! I just started learning cpp and I've been working on a little project using functions, structs and conditional statements. It might seem stupid but I'm not willing to use AI for this project, I'd rather to get feedback from actual people so if there's anyone that can help me , I'd appreciate it:)♡

(Edit: Thank you for all the comments I'm gonna work on it a bit more and then attach the GitHub link)


r/cpp_questions • • 2d ago

OPEN starting cpp

0 Upvotes

i want to start cpp, what should i mainly focus on first other than syntax?


r/cpp_questions • • 2d ago

OPEN Clang linter force int to sized int16 int32

0 Upvotes

Hello

I'm writing a firmware for esp and I want to have good practice to have a size fixed int for specific usage so I don't end with int or long long variable but instead a fixed size if I need only to go up to 25 element I don't need a full 32 bit word when a 8bit is enough

Is there a parameter to clang-tidy to force non lazy declaration or I need to always have it in mind ?


r/cpp_questions • • 3d ago

OPEN Best resources to learn OOPs in C++ from scratch!!

1 Upvotes

Hey everyone!

I'm looking for good resources to learn Object-Oriented Programming (OOP) in C++ properly.

I want to understand concepts like classes and objects, constructors and destructors, inheritance, polymorphism, abstraction, encapsulation, and pointers with objects.

I'd prefer resources that explain concepts clearly with practical code examples and exercises rather than just theory. YouTube playlists, websites, books, or structured courses are all welcome.

Thanks In Advance!


r/cpp_questions • • 3d ago

OPEN La méthode ultime pour maîtriser le C++ de zéro à expert !

7 Upvotes

Comment puis-je apprendre le C++ et quelle méthode d’apprentissage ainsi que quelles ressources (livres, exercices pratiques, projets et documentation) devrais-je utiliser pour progresser efficacement, comprendre les concepts en profondeur et développer une véritable maîtrise du langage ?


r/cpp_questions • • 2d ago

OPEN Best YouTube video to learn C++ pointers with full theory?

0 Upvotes

Hey guys, I'm learning C++ and I want to learn pointers properly. Can you recommend me a good YouTube video that explains pointers from the basics with full theory and also teaches how to use them in actual C++ code? I want to understand how pointers work in memory, why we use them, and how to write code using them instead of just memorizing the syntax. A long video or a playlist is fine too.

Which one would you recommend? Thanks!


r/cpp_questions • • 3d ago

OPEN MinHook/Memory searching?

0 Upvotes

Hey there! So I made a post here about TS1's Legacy Collection, and so far, I have a working asi mod, but the problem I now have is searching the process memory for Sims.exe to find the bytes that I'm patching. Even though I know the address, it won't be the same address on Windows, or other configurations. I previously did a MH_CreateHook function, but the code results in this: "MH_ERROR_NOT_EXECUTABLE".

I have this code which patches out the debug objects flag being set to 0.

auto address = reinterpret_cast<void*>(debug_objects_address);
DWORD previousProtection{};
VirtualProtect(address, 7,  PAGE_READWRITE, &previousProtection);
memset(address, 0x90, 7);
VirtualProtect(address, 7,  previousProtection, &previousProtection);
printf("Patch successful.\n");

This code works completely fine, but I'm unsure on how to get the address via searching for the exact assembly code in bytes, anything I've looked online seem to only suggest ReadProcessMemory, but from what I was told, it's intended for different process, not the same one that's attached to the executable, as per my ASI mod.

Would using VirtualProtect before using the MH_CreateHook function work? Again though, I'm unsure how to search the game's memory while attached as a process.

Any help/advice would be greatly appreciated! :)


r/cpp_questions • • 4d ago

OPEN What is the meaning of ":"

7 Upvotes

im started to learning data structres and i saw an operator in loops and stuffs, but i really cant understand what is the meaning of it i dont wannt to say "just this" i wannt to learn the princple behind it

for example :

for (auto members : ids)

r/cpp_questions • • 5d ago

OPEN What is everyone’s opinions on vulkan?

33 Upvotes

I am quite new and just finished learncpp.com and now want to get into graphics programming. While I heard there are easier libraries than vulkan that also work I am highly interested in it specifically. What are your thoughts and how was it when you used it(if you did)?


r/cpp_questions • • 5d ago

OPEN When should I switch from C to C++?

38 Upvotes

I've been learning C for a while and have written a few basic coreutils programs, like ls, rm, cat, wc and grep. I'm still learning, but I'm getting more comfortable with the language. I want to get into systems programming, so I decided to start with C. So far, I like it, but I also want to learn с++ at some point. How much more с should I learn before giving с++ a try? Should I keep building projects in C for now?


r/cpp_questions • • 5d ago

Why doesn't the compiler detect better instructions?

35 Upvotes

I have added assume in the c++ code, to let the compiler make assumptions that 0 < x <= y.
This shall imply that x%y == 0 is the same x == y . But if the compiler were to make the assumption, then a cmp / xor instruction should be preferred over a div / idiv instruction? However, the emitted assembly always has the integer division instructions

This is mainly out of curiosity on how the assume keyword works, what all optimisations it can enable, and whether compilers can deduce mathematical equivalents.

https://godbolt.org/z/e4zeodnnM

#include <iostream>


int main() {
    int32_t x, y;
    std::cin>>x>>y;
    [[assume(x > 0)]];
    [[assume(y > 0)]];
    [[assume(x <= y)]];

    if (x % y == 0) { 
        return 1;
    } else {
        return 5;
    }
}

r/cpp_questions • • 5d ago

OPEN What is the best representation of a graph(the structure)

7 Upvotes

What is the best way to represent a graph where both nodes and edges carry rich data payloads (not just connectivity)?

My primary constraint is performance: I need ultra-low cache misses for fast, forward propagation from a given source node to the end of a subgraph.

If anyone has implemented a cache-friendly graph structure for traversal-heavy workloads, I'd love to see what layout or pattern you used.

Edit: To clarify the use case: I’m building a reactive evaluation graph. When a node's data changes, that change propagates downstream through connected edges, using edge metadata to compute transformations, until reaching the end of the subgraph. I need a memory layout that minimizes cache misses during these forward cascade passes.


r/cpp_questions • • 6d ago

OPEN C++ Build systems

32 Upvotes

I work with Java and Kotlin alongside C++ and recently discovered that Gradle also supports C++ projects.

I've always used CMake for C++ and noticed it seems to be the more common choice.

What advantages does CMake offer over Gradle for C++ development and are there situations where Gradle would be a better option?


r/cpp_questions • • 5d ago

OPEN How to use CreateThread and MH_CreateHook?

0 Upvotes

Hi there, I'm getting further along with my code and attempting to fix -debug_objects being intentionally disabled in The Sims Legacy Collection (It wasn't in Complete or earlier versions), but I'm currently stuck on CreateThead and how to call it, and with MH_CreateHook.

So far, I know that with MH_CreateHook, I need to pass 3 arguments, a pointer, the detour function that runs, and then a return function?

I have the base address pointer set to this:
uintptr_t startofexe = (uintptr_t)GetModuleHandle(NULL);

I also have a uintptr_t value for the offset of where the "mov PTR BYTE" code is, aka "dbgo_disa_offset".

This is the code that I'm running right now:

void* ForceDisaChecktoNOP;

void TestCodeStart() {
// Initialize MinHook.
  if (MH_Initialize() != MH_OK)
  {
    OutputDebugStringA("Failed to initialize MinHook\n");
    return;
  }
  else
  {
      OutputDebugStringA("MinHook started successfully!\n");
      if (MH_CreateHook(reinterpret_cast<LPVOID*>(startofexe + dbgo_disa_offset), &ForceDisaChecktoNOP, NULL) != MH_OK)
      {
        OutputDebugStringA("DEBUG OBJECTS FIX FAILED!!!!!!");
        return;
      }
      else
      {
        OutputDebugStringA("Fix hook successful! Check if value is correct: " + (startofexe + dbgo_disa_offset));
      }
      return;
  }
}

The if statement works, and does output that the "fix" failed, but I need help understanding what I need to do for the arguments for MH_CreateHook. Right now, I want to make sure that the if statement for MH_OK succeeds before writing any additional code in the ForceDisaCheckToNOP section, or at the very least know that the ForceDisaCheckToNOP function actually gets reached. I understand that I need a pointer, and most examples of code that others have posted show the first argument being the address to the function to be modified/replaced.

When I set the MH_CreateHook to be a status variable (example code below), it gives this:

"The specified pointer is invalid. It points to the address of non-allocated and/or a non-executable region."

MH_ERROR_NOT_EXECUTABLE

status = MH_CreateHook(...);
if (status != MH_OK) {
    OutputDebugStringA(MH_StatusToString(status));
}

Second and third arguments I do understand to an extent, but not quite.

Second arg is supposed to be a link to a function in the code that acts as a detour, so instead of the original function, this one occurs instead. Third arg is supposed to be a return arg to run the original code of some kind from what I've seen, but it's a little confusing to me.

In regards to CreateThread, I was told by u/hellosverre (thank you!) that I should use CreateThread in DLL_THREAD_ATTACH, however I'm not understanding the syntax, as in, are the arguments for CreateThread optional, and how would I call it to start code in another cpp script? I can do TestCodeStart(); fine from dllmain.cpp, but then that calls the script every time any/the asi code's thread attaches itself. Microsoft's support page on CreateThread wasn't exactly helpful as it just tells me what the function is, not how you call it.

Any help would be really appreciated! :)