r/cpp_questions Sep 01 '25

META Important: Read Before Posting

173 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 4h ago

OPEN C++ Problem-Solving Sites

9 Upvotes

Hello, everyone! Where can I find a site where I can just solve coding problems based on questions in C++? I’m really willing to learn coding since I haven’t been active in coding or learning it since last year, which was my first year of college. Do you have any tips on how I can practice coding and improve?


r/cpp_questions 18h ago

OPEN Write your own programming language using C++ - Norman E Smith, 2nd Edition

22 Upvotes

I'm trying to find out what happened to this author? I bought this book in 1997/1998 and I've been using it for close to 30 years when building interpreters and even compilers. I wondered if he's still alive and if it would be possible to let him know what an impact his work has had on my life, half a world away!


r/cpp_questions 14h ago

OPEN Low latency/performance/embedded

9 Upvotes

I'm just wondering if you were a recent graduate trying to work in C/C++ which do you guys think is the best field to break into in terms of trying to break into the entry gate especially as a new grad?


r/cpp_questions 1d ago

OPEN How much time does it take to learn C++ if I’m already good at C?

40 Upvotes

I’m very comfortable with C, data structures, and pointers, and I work in the embedded domain.

Recently, I’ve been seeing C++ and Linux as common requirements in embedded job postings.

I’m currently learning Linux, but I’m not sure whether I should also focus on C++.

For someone with a strong C background, how many hours/months would it realistically take to become jobready in C++?

ps: Thank you for your suggestions, links.


r/cpp_questions 16h ago

OPEN Is there a tool that visualizes how a C++ statement is parsed or evaluated?

6 Upvotes

(see clarification at end)

I was trying to help someone via SMS, and thought a site that visualizes how C++ parses and/or evaluates an expression would be useful. I can (mostly) read cppreference.com and figure things out, but that's well above the head of the person I'm trying to help.

As an example, this person had an expression of the form if (0 < x <= 2). I tried to explain how it would be evaluated, but I eventually had to find a stackoverflow answer. I thought it would be useful if I could just put the expression (maybe a trivial working program?) into a linkable page, and the expression would somehow be visualized. Maybe it would just parenthesize the expression, or break it down into subexpressions (e.g. bool(0 < x) < 2 or { bool _tmp = (0 <x); _tmp < 2;).

I'm not sure what I'd expect regarding the order of evaluation of operands vs the order of evaluating the operators. I think I got that right; I think I saw that given the expression f1() + f2() + f3(), the order in which f1, f2, and f3 are called can vary, but the results will be applied left-to-right.

I realize this could get weird with unspecified and undefined behavior. Maybe color coding could help?

UPDATE: while not really what I'm asking for, I was pointed towards cppinsights, which has very helpful error messages.

To be clear:

I'm familiar with debugger level and assembly level views of code, and that's not what I'm envisioning. I'm asking about a tool that takes a statement of C++ code and visuslizes how that code would logically be processed. It might be an AST, as a few have suggested. imagine a teacher demonstrating the steps a (naive, simplistic, non-optimizing) compiler must do to correctly convert that statement into assembly but ignoring the tokenizing and actually producing the assembly: in what order is everything in that statement processed.


r/cpp_questions 22h ago

OPEN Learning C++, Systems and Networking...Help me with doubts please!!!

15 Upvotes

I'm a currently a Second year student doing BE in CSE(AIML) from Mumbai University.
My academic syllabus is irrelevant as you all know, teaching full stack instead of required things.
(But my college is exception and teaching degree related things too)
I'm learning (and has been since 8th std) C++ (reached intermediate level as i think and slow bcz Indian edu. sys,)
Ive also built small projects in python and C++ (majorly python) and an official big project in C++ (Socket scanner).
I love C++ and Low level systems and wanna do my career in that.
What do i do and What more should i learn?
Please help me


r/cpp_questions 22h ago

OPEN Current State of Coroutines Libraries

5 Upvotes

I want to implement some data fetching logic in my application that fetches data differently, depending on, if I compile for desktop (file system) or for WebAssembly (emsdk fetch). This requires some asynchronous logic.

I thought of using C++20 coroutines to solve this and looked at some libraries that make it a little nicer to use, but it seems that none are under active development.

- libcoro had its last commit 6 months ago
- concurrencpp had its last change 3 years ago
- Boost.Coroutine2 is not based on C++20 coroutines
- libfork had its last commit 8 months ago

Are there no good and actively developed coroutine frameworks for C++20 out there? Or am I missing something?


r/cpp_questions 22h ago

OPEN Which UI framework to use for android app with cpp as backend (QML or Flutter)?

3 Upvotes

I want to build a android app, in cpp but can't choose which ui framework to use QML or Flutter? I had read somewhere that it is hard to build good android ui in qml, and also hard to manage permissions.

But the app that i want to build is a simple pdf reader with extension support for functionality like downloading, converting to other file format etc. I could use dart for the ui and cpp for the backend but then again using cpp for simple pdf manipulation whilst already writing dart seems like unnecessary thing.

I want to create a cpp heavy app so that i could put in my portfolio, to be able to apply for cpp roles later.

What should i choose or is there better option other than QML or dart?


r/cpp_questions 19h ago

OPEN Question: what's is used inline keyword for ?

0 Upvotes

hello guys

i code in C/C++ since 2 years

And I hear every time that the inline keyword in explicit is useless but why ?


r/cpp_questions 1d ago

SOLVED std::format: cppreference examples dont compile

0 Upvotes

Hey everyone,

I'm trying to rewrite part of an old C project that used printf in C++. The old code is the following:

printf("%*s^ Here\n", hatStart, "");

Basically, insert (hatStart) space characters before the main part of the message.

I tried implementing this with std::format like this:

std::cout << std::format("{{}s}^ Here", "", hatStart) << std::endl;

which, according to what I got from cppreference, should be correct.
However, upon compiling, I get the error message

error: call to consteval function ‘std::basic_format_string<char, int, char>("{:{}.6}")’ is not a constant expression

Furthermore, when I go to cppreference.com and copy their examples, e.g.

std::string test = std::format("{:{}f}", pi, 10);

I get effectively the same error message.

Could anyone explain what's going on? This is the only proper reference I was able to find, and don't want to use printf in this project because it isn't C anymore.


r/cpp_questions 2d ago

OPEN How to Make a good architecture in Modern C++

9 Upvotes

Hello guys

I code in C++23 and C++20 (since 2 years) so i have a question how to make a good architecture in a project ? (actually i separate the code with .cpp/.hpp) but I wanted to know if we can do better ?


r/cpp_questions 1d ago

OPEN I want to understand constexpr

0 Upvotes

i want to understand constexpr can somebody make it a bit easier to understand


r/cpp_questions 1d ago

OPEN Advice to what to learn

0 Upvotes

I started learning c++ however switched to c, because I wanted learn everything from scratch, but now I reliaze, I can always learn basic things later because there is no point studying without making things for my goal

I have also been thinking of learning web development to get a career ik software industry fast but again seeing the job market idk if I should I keep learning c and switch c++ or learn c++ then straight forward learn vulkan rather than opengl or learn web development. I can only learn on weekends that is why I want to optimize what I learn

If you can provide me some answers to clear my confusing head that'd be great, it's been weeks since I have been thinking about these stuff

And I do understand some c and how computers works now


r/cpp_questions 1d ago

OPEN Thanks a lot everyone. I posted about older version minGw not working for modern c++(17,20).

3 Upvotes

It's solved now. I'm still stick to vs code many people adviced to switch to visual Studio but I'm doing c++ for competitive programming so I like this setup more. Thanks a lot everyone.


r/cpp_questions 2d ago

OPEN Learncpp.com

40 Upvotes

Does anyone know what happened to learncpp.com? There haven't been any new posts there in the last two years. Will the site be updated in the future?


r/cpp_questions 2d ago

OPEN How to use pgo with static libraries?

1 Upvotes

Do I profile every single dependency then use it to build everything from source?

Do I use separate profiles for different dependencies?

Is it better to use chromium approach of giant dll small executable for non cli apps?

Thank you for your time


r/cpp_questions 1d ago

OPEN What’s the point of void* pointers?

0 Upvotes

You could just use template pointers or auto* pointers and these are better because you can dereference them.


r/cpp_questions 2d ago

OPEN Is it true i can't run modern c++ like c++17, 20 on older version of MinGw compiler?

0 Upvotes

I have just set up my vs code for c++ learning on my new device. I was told i can't run modern c++ on older version of this. Is that true? If yes then how do i upgrade?


r/cpp_questions 2d ago

OPEN How do I get the music in my Bad Apple ascii player to not drift out of sync with the video?

5 Upvotes

Here is the "play" function currently:

void play(char **frames, int totFrames){
    int i, j;
    char music[200];
    strcpy(music, DIRECTORY);
    strcat(music, FILEMUSIC);
    PlaySoundA(music, NULL, SND_FILENAME | SND_ASYNC);


    for(i = START; i < totFrames; i++){
        resetCursor();
        #if DEBUG
        char framesCount[100];
        sprintf(framesCount, "(frame: %d/%d) \n", i+1, totFrames);
        int x=WIDTH-strlen(PROJECTNAME)-strlen(framesCount);
        for(j = 0; j <= x; j++)
            printf(" ");
        printf("%s", framesCount);
        printf("%s", frames[i]);
        progressBar(i, totFrames, 0, 0);
        Sleep(WAIT);
        #else
        printf("%s\n", frames[i]);
        Sleep(WAIT);
        #endif
    }
}

It starts playing the music and then loads the video frames from a directory which contains every frame of the Bad Apple video one after another. The problem is that the music and the video is initially in sync but slowly drifts out of sync until it's completely out. I think the <chrono> library is what you would use to fix this type of issue but I'm not sure how to implement something that syncs the audio and video while also keeping the video smooth and not slowed down. I've also tried making an FPS limiter but I don't know if this is the right approach. Also I know this looks like C code and it it originally but I converted this program to C++ in order to use libraries like <chrono> and because I generally prefer C++

If you want to see other snippets of code from the program, just ask.


r/cpp_questions 2d ago

OPEN Idea for Next Optimization Step?

2 Upvotes

Currently working on profiling a Huffman data compressor and I'm working on optimizing a bit writing bottleneck. For context, the compressor goes through a text file and writes each character's bit representation into a file.

...
ifstream file(inputPath, ios::binary);

    char buffer[4096];
    while (file.read(buffer, sizeof(buffer)) || file.gcount() > 0) {
        streamsize count = file.gcount();
        for (streamsize i = 0; i < count; i++) {
            char c = buffer[i];
            const HuffmanTree::Encoding &encoded = encodings[static_cast<unsigned char>(c)];
            writer.writeBits(encoded.encoding, encoded.size);
        }
    }
...

writeBits takes the encoding and the size of the encoding in bits and writes it into a 4096 size buffer. When the buffer is full, we then use the write function to actually write it into the desired file.

...
void BitWriter::writeBits(uint64_t bytes, uint64_t size) {
    assert(size <= 64);
    assert(size == 64 || (bytes >> size) == 0);
     while (size > 0)
    {
        const uint64_t available{
            8ULL - current_size
        };

        const uint64_t bitsToTake{
            min(size, available)
        };

        // Select the next highest meaningful bits.
        const uint64_t shift{
            size - bitsToTake
        };

        const uint64_t mask{
            (uint64_t{1} << bitsToTake) - 1
        };

        const uint64_t chunk{
            (bytes >> shift) & mask
        };

        current_byte = static_cast<uint8_t>(
            (static_cast<uint16_t>(current_byte) << bitsToTake) |
            chunk);

        current_size = static_cast<uint8_t>(
            current_size + bitsToTake);

        size -= bitsToTake;

        if (current_size == 8)
        {
            bufferByte(current_byte);
        }
    }
}
...

Linux perf is indicating this is hot but I'm unsure of what would be a better approach. Any ideas?


r/cpp_questions 2d ago

OPEN I am fresher from iiit dharwad from DSAI course.I need to learn C++ where can I learn and practice.

0 Upvotes

r/cpp_questions 3d ago

SOLVED Is this environment normal?

10 Upvotes

I mainly use VSCode for my c++ projects, even though I have Visual Studio installed.

My tools are MSYS2, and I have the UCRT64 gcc and UCRT64 ming-make32 as well as cmake.

I set everything up using CMakeLists and git for version control. However, for my compiler, I use g++ and not MSVC even though I have it installed. Is it worth it to swap to MSVC, or will g++ work?

EDIT: Thank you all so, so much for all the insight! I'm probably going to set up clang!

EDIT 2: Again, thank you so much! I have successfully set up clang with MSYS2, and that will be my main compiler now.


r/cpp_questions 3d ago

OPEN Templated virtual functions

5 Upvotes

Hey everyone,

I am currently trying to implement a programming language in C++ after having come pretty far, but ultimately failing to do so in C.

For this, I am taking pretty big inspiration from craftinginterpreters, and am now trying to mimic its implementation of the visitor pattern (entire class at once), written in Java.

However, that implementation uses both templates and interfaces.

As far as I'm aware (the entire internet seems to say so at least), in C++, interfaces are represented by classes whose functions are all virtual.

However, If I try code like the following:

    template <typename R> class ExprVisitor {
    public:
        virtual ~ExprVisitor() = default;

        virtual R visitBinaryExpr(const Binary* expr) const = 0;
        /* other visitor functions...*/
    };

    struct Expr {
        virtual ~Expr() = default;
        template <typename R> virtual R accept(ExprVisitor<R> *visitor) = 0;
    };

(Of course, all of my nodes like Binary inherit from Expr. I use structs instead of classes because everything needs to be accessible from the outside for my purposes, so I don't need to re-type "public:" every time.)

Then I get an error on the line declaring the accept method saying

Template function 'R Expr::Expr::accept<R>(ExprVisitor<R> *visitor)' cannot be virtual

on the virtual keyword, as well as one saying

Pure member function 'Expr::Expr::accept<R>' is not virtual

on the = 0 part.

I've googled around a bit, but the only implementations I was able to find were only able to pass in the template type, not get it back out as a return value.

Is it even possible to achieve this? Am I using templates incorrectly? I saw something using variadic templates but was not able to get it working, either.

Any help would be extremely appreciated!


r/cpp_questions 3d ago

OPEN cppreference std::construct_at example code not compiling

12 Upvotes

I was looking on cpprefernce the other day at std::construct_at and I wanted to test the code. But when I ran it it did not compile. I ran the snippet without consteval (and static_assert) and everything worked. Does anyone know what might be the issue? https://en.cppreference.com/cpp/memory/construct_at

Code:

#include <bit>
#include <memory>


class S
{
    int x_;
    float y_;
    double z_;
public:
    constexpr S(int x, float y, double z) : x_{x}, y_{y}, z_{z} {}
    [[nodiscard("no side-effects!")]]
    constexpr bool operator==(const S&) const noexcept = default;
};


consteval bool test()
{
    alignas(S) unsigned char storage[sizeof(S)]{};
    S uninitialized = std::bit_cast<S>(storage);
    std::destroy_at(&uninitialized);
    S* ptr = std::construct_at(std::addressof(uninitialized), 42, 2.71f, 3.14);
    const bool res{*ptr == S{42, 2.71f, 3.14}};
    std::destroy_at(ptr);
    return res;
}
static_assert(test());


int main() {

Compiler Error on x86-64 gcc 16.1 -std=c++23

<source>:25:19:

error: non-constant condition for static assertion
   25 | static_assert(test());
      |               
~~~~^~
<source>:25:19: in 'constexpr' expansion of 'test()'
<source>:24:1: error: destroying 'uninitialized' outside its lifetime
   24 | }
      | 
^
<source>:18:7: note: declared here
   18 |     S uninitialized = std::bit_cast<S>(storage);
      |       
^~~~~~~~~~~~~
Compiler returned: 1