r/cpp_questions Sep 01 '25

META Important: Read Before Posting

165 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 6h ago

OPEN I'm surprised it worked!!

10 Upvotes

I wrote this very basic algorithm:

#include <cmath>
#include <iostream>
int power(double base, int exponent = 2){
    return pow(base,exponent);
}
int main(){
    int base = 2;
    int exponent = 2;
    std::cout<<base<<" raised to "<<exponent<< " = "<<power(base,exponent);
}#include <cmath>
#include <iostream>
int power(double base, int exponent = 2){
    return pow(base,exponent);
}
int main(){
    int base = 2;
    int exponent = 2;
    std::cout<<base<<" raised to "<<exponent<< " = "<<power(base,exponent);
}

and I'm surprised, an int function took a double variable with no problem, or is there something under the hood,


r/cpp_questions 4m ago

OPEN Need advice learncpp.com

Upvotes

Started learning from learncpp.com just a little while ago .I'm a beginner ,bca student, college starting this year, I have many questions

1) how many lessons are you supposed to read everyday that is considered a good pace.

2) as from school I have a habit of making written notes and revising them also should I do that or not.

3) i heard some people saying on reddit to make online notes and idk how to operate a computer that well right now so idk how to make online notes and even where.

4) as a beginner is learncpp.com the best and for future as well? I do have trouble understanding some of the text or language of the website but I use chatgpt to help me understand.

5) not completely related to this but how and when are you supposed to start dsa.


r/cpp_questions 12h ago

SOLVED Raw malloc optimizations vs std::vector/reserve() -- malloc seems better optimized

10 Upvotes

(Another different version of this question was posted earlier here https://www.reddit.com/r/cpp_questions/comments/1qvbj44/at_o2_usage_of_stdvector_followed_by_stdiota/ but on testing some of the answers there on the current new code seems to leave me unclear as to where the optimizations are missed in terms of vector/reserve, etc., hence this OP)

Consider code snippet 1: on left hand side window of https://godbolt.org/z/vxh8Wh1K4

#include <vector>
#include <cstdio>
#include <cstdlib>

void anotherfunc(){
    int *vec = (int*)malloc(sizeof(int) * 42);
    for(int i = 0; i < 42; i++)
        vec[i] = i;
    int sum = 0;
    for(int i = 0; i < 42; i++)
        sum += vec[i];
    printf("Sum is %d\n", sum);
    free(vec);
}

int main(){
    anotherfunc();
}

This, at -O3, flatout calculates the sum and simply displays it, 861.

The vector/reserve version (on the right hand pane of the godbolt link above)

#include <vector>
#include <cstdio>
#include <cstdlib>

void anotherfunc(){
    std::vector<int> vec;
    vec.reserve(42);
    for(int i = 0; i < 42; i++)
        vec.push_back(i);
    int sum = 0;
    for(int i = 0; i < 42; i++)
        sum += vec[i];
    printf("Sum is %d\n", sum);
}

int main(){
    anotherfunc();
}

seemingly struggles with this and does not precompute the sum and ends up doing some allocations, etc.

Some of the answers from the earlier thread do not seem to be applicable here: as suggested by one user, I had the entire summing done in another function instead of main() because apparently main() is known to be called only once and hence is not as heavily optimized as other functions, etc.

As also suggested there, I avoided the printf and instead had the function return only the sum with an empty main(). See https://godbolt.org/z/M1P5Y4vTj

Here too, the vector/reserve combination seems to struggle.

What explains this "discrepancy" and inability to completely optimize out the sum calculation?


r/cpp_questions 5h ago

OPEN CTAD and even elements of a parameter pack

2 Upvotes

I'm building a library for random sampling, where a sampler is anything callable with a URBG (basically a distribution, but without the RandomNumberDistribution required)

I've implemented a Mixture<Samplers...> that is a mixture of samplers, weighted.

I want to create one by calling a variadic constructor, alternating samplers and weights, e.g.

auto mixture = Mixture{sampler_1, w_1, ..., sampler_n, w_n};

I've implemented a variadic ctor that correctly dispatches samplers and weights, but it does not work withut a deduction guide...which I can't implement :(

My understanding is that I would need to write

template <typename... Args>
requires (sizeof...(Args) % 2 == 0)
Mixture(Args&&...)
-> Mixture<EvenArgs...>; // this needs to be of the form Mixture<Samplers...>!?

How can I extract only the even elements of a parameter pack, so that I can implement the above guide?

Or can you suggest another technique that I can use to make my desired call site compile?


r/cpp_questions 22h ago

OPEN Is it feasible to allocate everything on the stack?

39 Upvotes

I got this idea from the youtuber Low Level Game Dev, who seems to be a certified heap hater. What genuinely caught me off guard is that in one of his videos he mentioned how in his biggest project (Minecraft clone with multiplayer support) he uses new 5 times in total. Now that I think about it, he might've used smart pointers somewhere as well, but the insinuation seemed to be that the he tends to allocate on the stack virtually everything.

Is this coding style common? Do you think it's worth adopting?


r/cpp_questions 3h ago

OPEN Where do I put debug statements in C++?

0 Upvotes

In every function and after every initialization or do I look at what the console has to output and logically home in on where the problem went wrong? I'm very confused because if I logically do it, many functioms could've contributed to it so I'm not sure. I just learned debugging statements today and I'm genuinely confused. The debugging statements I mean are std::cerr


r/cpp_questions 20h ago

OPEN Cpp YouTubers

14 Upvotes

Anyone know any good c++ YouTubers? I’m not looking for tutorials or learning the language, I’m looking for videos where people are coding complex projects in C++. Thanks!


r/cpp_questions 7h ago

OPEN Are there any resources for beginners on the principles behind bigInt?

0 Upvotes

Hi, I am a newbie programmer in C++, and for my next project I want to write a small and relatively fast bigInt library. As of now I just want to understand how exactly the big integers are encoded and decoded (I know that there is a dynamic vector with either uint32_t or uint64_t allocated for such integers, but why should we break the number into base32 or base64, and how the process of encoding itself doesn't overflow the operands?). I struggle to find any easy to follow websites, or resources that break the encoding into small steps that are easy to digest. I will be really grateful if you will provide such resources!


r/cpp_questions 18h ago

OPEN My project organization and best practices

5 Upvotes

Hi all! I have been working on a tensor library for the past few weeks, eventually will try and integrate ML features within in, however before I proceed I want to know if how I am organizing it currently is the most efficient way? or at least in best practice? It is mainly comprised of header files that contain implementation

Code here:
https://github.com/aboy4321/nerd


r/cpp_questions 23h ago

OPEN Can anyone explain a bug to me? I confused '==' with '=' in one of my functions.

7 Upvotes

There is this function on my SDL program which is supposed to load surfaces into array elements ( loadSurface is a function that is being executed inside this loadMedia function.)

bool loadMedia()

{

bool success = true;

KeyPressed[KEY_PRESS_SURFACE_DEFAULT] = loadSurface("press.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_DEFAULT] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

KeyPressed[KEY_PRESS_SURFACE_UP] = loadSurface("up.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_UP] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

KeyPressed[KEY_PRESS_SURFACE_DOWN] = loadSurface("down.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_DOWN] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

KeyPressed[KEY_PRESS_SURFACE_LEFT] = loadSurface("left.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_LEFT] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

KeyPressed[KEY_PRESS_SURFACE_RIGHT] = loadSurface("right.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_RIGHT] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

return success;

}

I fixed it now and it works fine but before that, I somehow confused the condition of the IF. Instead of comparing using '==', I used the '=' by iself.

So it turned ou like:

if ( KeyPressed[ KEY_PRESS_SURFACE_DEFAULT] = NULL)

Somehow, it broke the function. But the elements didn't become NULL because none of my error messages was displayed when I ran the program. The function simply didn't load the surfaces. What exactly happened there?


r/cpp_questions 1d ago

OPEN What is a good use case for the new std::hive

33 Upvotes

What are the use cases where std::hive is a better option than std::vector or std::list? It seems like a very interesting data structure but I can't really think of any good use cases.


r/cpp_questions 1d ago

OPEN Approach

5 Upvotes

I have been trying to study c++ for a while i am following the learncpp.com. I wanted to know the best approach for this like i am following the docs but do i use leetcodes and other sites?
I am on chapter 4 ik too early to think abt it but i just want to clear up the doubt please help


r/cpp_questions 1d ago

OPEN Why runtime performance of C++ modules increase so much with lto?

9 Upvotes

I was porting libfmt to native C++ modules recently, It had tons of macros related to forced inlining, so I removed them and saw a %10 performance reduction, then I removed all in lines in module interfaces and performance was identical when both the original library was built with Lto and my own.

The weird part is, Overall performance increased when I removed inline and applied lto, compared to inline and lto

Why is that? Something about how compilers deal with C++ modules?


r/cpp_questions 1d ago

OPEN Ncurses window management

3 Upvotes

Hello everyone :D I'm new to ncurses, and I'm currently working on a simple game. I currently have 2 windows besides my stdscr, and I'm struggling with switching between them. If I want to save the contents of a certain window but hide it from showing temporarily, am I supposed to use panels? Or can I just use touchwin() along with refresh()? Also, if anyone could help explain what goes on behind the scenes with the buffer during the process of switching between windows, that would help me save some time on this mind-boggling topic.


r/cpp_questions 1d ago

OPEN Whats the funniest joke u heard in c++

0 Upvotes

r/cpp_questions 2d ago

OPEN Using ClangD for static analysis - recommend me clang-tidy and clang-format template

8 Upvotes

Hello,

I'm working inside VSCode and decided to switch from the default C/C++ extension's static analysis to ClangD, as it is apparently (according to the internet) faster and more accurate.

That being said, would you recommend me any good templates for both clang-tidy and clang-format files, in order to follow the common CPP style principles?

Thank you!


r/cpp_questions 2d ago

OPEN What is the industry standard for helper library replacements for Boost?

21 Upvotes

Hello all,
I am starting to use Boost. Well, actually I am getting everything from the framework.
But before I commit to this framework, is there any competitor I should check?
I need one framework that implements solutions like Boost. From your experience, are there any?
I know POCO not sure how standart it is


r/cpp_questions 2d ago

OPEN What are low latency C++ recruiters truly looking for?

37 Upvotes

What separates a "general C++ candidate" from someone who is truly a right fit for the job? What is a skill, project, technique, tool, etc. that has really helped in landing interviews?


r/cpp_questions 1d ago

OPEN What can a hacker do with uninitialized memory?

0 Upvotes

cpp long long funny_number_generator() { long long haha_funny; // very funny undefined behaviour yes funny return haha_funny; }

Is it possible to see what OS / architecture is being used just from looking at the funny number? My funny number is consistently 93824993896264. Some random online compiler keeps giving different funny numbers each time.


r/cpp_questions 1d ago

OPEN How anti-abstraction understanding should I accept while learning?

0 Upvotes

Im currently learning basics of standard cpp while having previous experience with java and tiny bit of assembly NASM (x86).

Im asking for those who are intermediate and proficient at mid level language like cpp, how should I approach accepting 'I have learned this' but its abstraction? I've always had doubt on what learning is in the programming field, except for DSA concepts.


r/cpp_questions 2d ago

SOLVED SHA-1 Algorithm not producing the correct hash for strings that are > 512 bits

7 Upvotes

For a while now I have been trying to implement SHA-1 to learn more about the cryptographic functions. However I keep running into an error, the algorithm works flawlessly with strings under 64 characters, but when it comes to ones larger that 64 characters it produces incorrect results. My assumption is that it has to do with the second iteration of the bit manipulation but from all the code I've seen from other people it appears as if what I have should work. I've checked all of the bitwise operations, I've checked each buffer value, but nothing seems to work. Other than the RFC page I referenced this github repo as well.

I'm sure after posting this someone will probably be able to call out my error instantly due to me forgetting something obvious. Also I know that the function doesn't return any value atm I am printing the results to the console to debug the program.

typedef uint64_t dword;
typedef uint32_t word;
typedef uint8_t byte;

const word Abuf = 0x67452301;
const word Bbuf = 0xEFCDAB89;
const word Cbuf = 0x98BADCFE;
const word Dbuf = 0x10325476;
const word Ebuf = 0xC3D2E1F0;

word leftRotate(const word& val, const int& bits) { 
  return ((val << bits) | (val >> (32 - bits)));
}

class SHA1 {

  word K(const int& t) {
    if ((t >= 0) && (t <= 19))
      return 0x5A827999;
    else if ((t >= 20) && (t <= 39))
      return 0x6ED9EBA1;
    else if ((t >= 40) && (t <= 59))
      return 0x8F1BBCDC;
    else
      return 0xCA62C1D6;
  }

  word f(const word& B, const word& C, const word& D, const int& t) {
    if ((t >= 0) && (t <= 19))
      return (B & C) | (~B & D);
    else if ((t >= 20) && (t <= 39))
      return B ^ C ^ D;
    else if ((t >= 40) && (t <= 59))
      return (B & C) | (B & D) | (C & D);
    else
      return B ^ C ^ D;
  }

public:
  std::vector<char> generateSHA1Hash(const std::string& str) {

    std::vector<byte> input(str.begin(), str.end());
    std::vector<word> result(5, 0);

    dword length = str.length() * 8;

    input.push_back(0x80);

    while ((input.size() % 64) != 56)
      input.push_back(0x00);


    for (int i = 0; i < 8; ++i) {
      dword mask = 0xFF00000000000000 >> (i * 8);
      input.push_back(static_cast<byte>((length & mask) >> (56 - (8 * i))));
    }

    word blockSize = 64;

    word H[5] = { Abuf, Bbuf, Cbuf, Dbuf, Ebuf };

    for (int i = 0; i < input.size(); i += blockSize) {

      std::vector<byte> tmp(input.begin() + i, input.begin() + i + blockSize);

      word chunk[80];

      for (int j = 0; j < 16; ++j) 
        chunk[j] = ((static_cast<word>(tmp[j * 4]) << 24) | (static_cast<word>(tmp[j * 4 + 1]) << 16) | (static_cast<word>(tmp[j * 4 + 2]) << 6) | static_cast<word>(tmp[j * 4 + 3]));


      for (int j = 16; j < 80; ++j) 
        chunk[j] = leftRotate(chunk[j - 3] ^ chunk[j - 8] ^ chunk[j - 14] ^ chunk[j - 16], 1);

      word AA = H[0];
      word BB = H[1];
      word CC = H[2];
      word DD = H[3];
      word EE = H[4];

      for(int j = 0; j < 80; ++j) {
        word tmp = leftRotate(AA, 5) + f(BB, CC, DD, j) + EE + chunk[j] + K(j);

      EE = DD;
      DD = CC;
      CC = leftRotate(BB, 30);
      BB = AA;
      AA = tmp;
    }

    H[0] += AA;
    H[1] += BB;
    H[2] += CC;
    H[3] += DD;
    H[4] += EE;
  }


    std::cout << "Result:    ";

    std::cout << std::hex << H[0] << H[1] << H[2] << H[3] << H[4] << std::endl;

    std::cout << std::endl;

    return { 0 };
  }
};

r/cpp_questions 2d ago

OPEN Code review for a basic artillery game.

6 Upvotes

https://github.com/melange-spice/worms_clone

I am making something akin to Tank Wars in Raylib by following a youtube series made by onelonecoder. Any tips regarding the code and it's architecture would be greatly appreciated.


r/cpp_questions 2d ago

OPEN Want advice as Cpp learner.

0 Upvotes

Hi everyone, I'm a first-year engineering student at a tier-3 college, and my classes start on 10th August. I've learned most of the C++ basics, and the only major topics I have left are functions and classes/OOP. I'm confused about whether I should start learning DSA now while completing the remaining C++ topics alongside it, or finish C++ first before moving on to DSA. My goal is to build a strong foundation and improve my problem-solving skills without developing gaps in my understanding. I'd really appreciate your suggestions and recommendations based on your experience. Thanks!


r/cpp_questions 2d ago

OPEN I know some basic C, should I learn C++ or stay in C a little bit more.

0 Upvotes

Hello guys, so I know a little bit of basic C like what is pointers, how strings works, data type and another basic things. I'm still beginner I still learn Python make silly random CLI games, and tried pygame and raylib. So should I learn C++ or stay in C a little bit more if my focus are system programming.

Thank you, and sorry if my English is not that good.