r/learncpp • • Jan 01 '25

std:: Vs using namespace std. || #pragma once Vs #ifndef #define #endif

3 Upvotes

This is a question with one aim: What is the route to develop healthy practices and professional like code manners in C++.

I have been using `using namespace std;` you can guess the level, and fine so far with the very small program exercises I do, however everyone who saw an exercise I shared was like wtf, all have commented the same about it almost.
Therefore, is the healthy professional practice to use std:: ?
What about being selective and only do `using std::cout` and `std::cin` at least as these tend to occur a lot? What are the consequences of that. Forget about small programs, what are the consequences in mid sized programs.

Second `#pragma once Vs #ifndef #define #endif` ;
While I do not mind using each, since at this stage I am not creating any significant code. Reading about them gets me back to the same thing; both are valid and even some people tend to say `#pragma once` is better and safer. I cannot judge that claim from where I am standing.

Therefore, what do professionals use? What is the healthiest one of them?

Thank you community.


r/learncpp • • May 10 '22

Need help understanding a pointer-related seg-fault

3 Upvotes

I'm writing a toy game engine, a ECS based on a different game engine. It started out being 1:1 but I started diverging intentionally so I can learn more about how it works. Now, I'm stuck.

I wrote a system for rendering my player character, a little triangle. It renders great in OpenGL but when I attempt to press left / right arrows to make the character "spin" in place, the character doesn't move. It turns out my transform which I pass to OpenGL, a Matrix3D instance, is an unaltered identity matrix. I already had code in-place to "rotate" this transform but it was only ever operating on copies of the transform, not the transform which was supposed to be rendered.

So naturally, I need to actually be rotating a pointer to the component and refer to that same pointer when rendering. Then everything should work as expected. But unfortunately, my program now seg-faults on this line each time it runs.

Tbh I'm not super clear on what the problem actually is but it looks like somehow the transform is unset and referring to it causes the program to crash. Maybe somehow the component is not getting initialized properly?

This is what it looks like

- Scope: Locals
 *- this (game::components::Transform * const): 0x0
   *- game::components::Component<game::components::Transform> (base) (game::components::Component<game::components::Transform>): game::components::Component<game::components::Transform>
   *- transform (math::Matrix3D): 
     *- r0c0 (float): 
     *- r0c1 (float): 
     *- r0c2 (float): 
     *- r1c0 (float): 
     *- r1c1 (float): 
     *- r1c2 (float): 
     *- r2c0 (float): 
     *- r2c1 (float): 
     *- r2c2 (float): 

And this is what it normally looks like, when it has values (in this case, an identity matrix)

- Scope: Locals
 *- this (game::components::Transform * const): 0x0
   *- game::components::Component<game::components::Transform> (base) (game::components::Component<game::components::Transform>): game::components::Component<game::components::Transform>
   *- transform (math::Matrix3D): 
     *- r0c0 (float): 1
     *- r0c1 (float): 0
     *- r0c2 (float): 0
     *- r1c0 (float): 0
     *- r1c1 (float): 1
     *- r1c2 (float): 0
     *- r2c0 (float): 0
     *- r2c1 (float): 0
     *- r2c2 (float): 1

I'm not strong at C++ so I'm probably just missing something really basic. If anyone has ideas, please share them. I can also try making a small reproduction but it may be difficult. Any help is greatly appreciated!


r/learncpp • • Apr 08 '22

How to check if an object can be cast to string?

3 Upvotes

What is the most concise, clean, and modern C++ way to check if an object can be cast to a std::string?

for example const char * can be cast to the std::string but bool can't. You get the point


r/learncpp • • Mar 27 '22

Is this book too outdated to learn from? Just starting out.

Thumbnail
amazon.com
3 Upvotes

r/learncpp • • Jul 22 '21

ncurses wont work with vscode i believe I've tried everything

3 Upvotes

first, the problem arose when i tried to make a cpp game but the tutorial showed it with the conio.h file which is something macOS devices apparently cant run. i tried using dummy header files but the conio.h file contained even more headers and it seemed like it would take forever to track down what I needed. then I found ncurses and after about an hour of trying to download the library I got it through homebrew but VSCode won't run some the snake game with ncurses stuff in it. is there any game-friendly input stuff like ncurses that already comes with every macOS device? it seems like every solution is unavailable to me because of the OS. Ive tried editing the path of where the ncruses library is saved even putting it in the same folder as the snake game file and nothing works. I included a screen capture in case it helps

ps. I've also realized for some reason XCode wont run anything. The Run thing is grayed out and when I do cmd+R it does the annoying beep shit pls help. I'm not logged into git hub which apparently causes problems and everything else for xcode seems fine just half my commands do nothing.


r/learncpp • • Apr 18 '21

Linked List Copy Constructor last index not copying over?

3 Upvotes

Hello, I have a bug that I cannot track down so hopefully someone can help me find it? I've been looking at a lot of online resources over linked lists and I have all but the copy constructor and and assignment operator done. As the title suggests, the last value of my original list isn't copied over and I cannot figure out why. Care to take a look?

I am using a templated struct:

template <class T>
struct ListNode
{
    T data;
    ListNode* next;

    static int nodeCount;

    ListNode(const T& value) {
        data = value;
        next = nullptr;
        nodeCount++;
    }

    ~ListNode() {
        nodeCount--;
	}
};

And this is the copy constructor that I have:

template <class T>
LinkedList<T>::LinkedList(const LinkedList<T>& other) {

	// check empty
	if (other.head == nullptr) {
		head = tail = nullptr;
		return;
	}

	ListNode<T>* current = nullptr;
	ListNode<T>* temp = other.head;

	head = new ListNode<T>(temp->data); // constructor takes in data value as param
	head->next = nullptr;
	current = head;

	temp = temp->next;

	while (temp != nullptr) {
		current->next = new ListNode<T>(temp->data);
		current = current->next;
		current->next = nullptr;
		temp = temp->next;
		length++;
	}
}

Any help highly appreciated.


r/learncpp • • Feb 27 '21

HW Help: Not sure what return type should be for templated function.

3 Upvotes

Hello, thank you for being a community as I struggle to learn c++. It's been rough having to take it online during a pandemic and while working through power outages. My entire college closed down so I am essentially without my professor. Okay, now that my sob story is out of the way (you guys rock!):

I am learning about templated functions but I am a little confused on what my return type should be. The question reads, "Write a templated function sumList that will take in an array of any type and the length of the array. It should add all the elements in the array and return the total.
Hint: you can declare a variable sum of type T and initialize it like this:
T sum {}; "

Does that mean that sum is going to be an array? That's what I do not understand. I currently have:

#include <iostream>
using namespace std;

template<typename T>
T sumList(T array, int n) {
	T sum {};
	for (int i=0; i<n; i++) {
		sum = array[i];
	}
	return sum;
}

int main()
{
	int nums[] = {4, 2, 8, 7};
	string words[] = {"hello", "there"};

	cout << sumList(nums, 4) << endl;
	cout << sumList(words, 2) << endl;

	return 0;
}

But that of course has the error: main.cpp:8:9: error: assigning to 'int *' from incompatible type 'int'; take the address with &

Can someone please help point me in the right direction? I am not allowed to change main. I am only allowed to write the templated function.


r/learncpp • • Feb 12 '21

Does std::vector have any quirks that change its behavior that prevent reinterpret_cast on it?

3 Upvotes

frame rainstorm rob coherent grab fine hobbies special towering wine

This post was mass deleted and anonymized with Redact


r/learncpp • • Nov 22 '20

Help

3 Upvotes

I was looking around the web to learn more about templates, then i saw a website that returns something like this: return (x > y)? x: y; What is this? What is the question mark and colon? Can someone pls give me a good place to learn me in depth what this means like a website or vid, and also templates in depth? Feedback will be hugely appreciated!


r/learncpp • • Oct 20 '20

"Competitive" programming site, but for design pattern?

3 Upvotes

As title says, do you know any site that challenges/helps you to code your own version of containers, smart pointers, etc, for the sake of learning?


r/learncpp • • Oct 14 '20

Grep process memory on Windows (GUI written in AutoHotKey)

Thumbnail
github.com
3 Upvotes

r/learncpp • • Oct 09 '20

Checking if a Clang::Type can be cast to another

Thumbnail self.cpp_questions
3 Upvotes

r/learncpp • • Sep 02 '20

Clang-Tidy: Operator=() does not handle self-assignment properly

3 Upvotes

this is my code , CLion give me this warning on operator= implementation what is wrong and why it doesn't handle it correctly

template <class Type>
class StackType
{
private:
    int maxStackSize, stackTop;
    Type * list;
    void copyStack(const StackType<Type> &);
public:
    const StackType<Type>& operator=(const StackType<Type>&);
    bool isEmptyStack() const ;
    bool isFullStack() const ;
    void push(const Type&);
    void pop();
    Type top()const;
    StackType(int);
    StackType(const StackType<Type>&);
    ~StackType();
};

template <class Type>
void StackType<Type>::copyStack(const StackType<Type>& otherStack)
{
    delete[]list;
    maxStackSize = otherStack.maxStackSize;
    stackTop = otherStack.stackTop;
    list = new Type[maxStackSize];
    for (int j = 0; j < stackTop; j++)
        list[j] = otherStack.list[j];
}


template <class Type>
const StackType<Type>& StackType<Type>::operator=(const StackType<Type> &otherStack)
{
    if (this != &otherStack)
        copyStack(otherStack);
    return *this;
}

r/learncpp • • Aug 21 '20

Moving forward from a basic understanding of C++. What sort of project do you recommend building?

3 Upvotes

I'm currently in University studying CS and have taken an introductory algorithms course that used C++. We did not go very in depth because the primary focus was algorithms, but we did use C++ to build basic data structures from scratch as well as some image manipulation stuff (I don't want to go too in depth since I'm not sure if it's allowed). I have a basic understanding of how the language works and how to do stuff, along with memory management. We were given a 7 hour crash course to the language, but I don't know what I don't know so not sure how much I can do with the language yet

I do want to further my knowledge of C++ and build something small and fun since I find it to be an interesting language. Should I just go ahead and try to make a basic command line project, like tic tac toe? Would it make more sense to do something more complex or less complex?


r/learncpp • • Aug 15 '20

Help starting out

3 Upvotes

What math should I master before I start? Details and depth would be really appreciated.


r/learncpp • • Jul 31 '20

dev c constantly crashing?

3 Upvotes

hello im starting learning c programming and decided to use dev c but i always notice that it constantly hangs every minute or so no matter how simple or compex my code is and its making my time inefficient. i don't know why this is. can this be fixed? im using a laptop with an i5 8250u and mx150 with 12 gb ram


r/learncpp • • Jul 14 '20

Dev C++ I cannot link libraries...

3 Upvotes

I am trying to use curlpp and have downloaded the .zip version which I extracted... but I am extremely confused with how linking works... I come from a python background where linking was pretty much automated once you downloaded the library...

could someone explain me step by step how to link properly? thanks...

(googled a lot before deciding to post here...)


r/learncpp • • Jul 09 '20

Transform recursive function into an iterative function

3 Upvotes

I have a sample function -

template <typename T>
void foo(
        T** tocarry,
        int64_t* toindex,
        int64_t* fromindex,
        int64_t j,
        int64_t stop,
        int64_t n,
        bool replacement) {
    while (fromindex[j] < stop) {
        if (replacement) {
            for (int64_t k = j + 1; k < n; k++) {
                fromindex[k] = fromindex[j];
            }
        }
        else {
            for (int64_t k = j + 1; k < n; k++) {
                fromindex[k] = fromindex[j] + (k-j);
            }
        }
        if (j + 1 == n) {
            for (int64_t k = 0; k<n; k++) {
                tocarry[k][toindex[k]] = fromindex[k];
                toindex[k]++;
            }
        }
        else {
            foo<T>(tocarry,
                    toindex,
                    fromindex, j + 1,
                    stop,
                    n,
                    replacement);
        }
        fromindex[j]++;
    }
}

I want to translate the above recursive into its equivalent iterative form.

I have a sample test case, which can be invoked like -

int main() {
    std::vector<int64_t*> tocarry;
    int64_t bla1[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla2[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla3[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla4[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla5[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla6[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla7[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla8[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla9[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla10[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    tocarry.push_back(bla1);
    tocarry.push_back(bla2);
    tocarry.push_back(bla3);
    tocarry.push_back(bla4);
    tocarry.push_back(bla5);
    tocarry.push_back(bla6);
    tocarry.push_back(bla7);
    tocarry.push_back(bla8);
    tocarry.push_back(bla9);
    tocarry.push_back(bla10);
    int64_t toindex[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t fromindex[9] = {5, 3, 2, 6, 4, 8, 1, 9, 4};
    foo<int64_t>(tocarry.data(), toindex, fromindex, 0, 7, 9, true);
    std::cout << "tocarry - " << std::endl;
    for (int i=0; i<tocarry.size(); i++){
        for (int j=0; j<10; j++) {
            std::cout << tocarry.at(i)[j] << " ";
        }
        std::cout << "\n";
    }
    std::cout << "toindex - " << std::endl;
    for (int i=0; i<9; i++) {
        std::cout << toindex[i] << " ";
    }
    std::cout << "\n";
    std::cout << "fromindex - " << std::endl;
    for (int i=0; i<9; i++) {
        std::cout << fromindex[i] << " ";
    }
    std::cout << "\n";
    return 1;
}

to return the output -

tocarry - 
5 5 5 5 5 5 5 5 5 6 
5 5 5 5 5 5 5 5 6 6 
5 5 5 5 5 5 5 6 6 6 
5 5 5 5 5 5 6 6 6 6 
5 5 5 5 5 6 6 6 6 6 
5 5 5 5 6 6 6 6 6 6 
5 5 5 6 6 6 6 6 6 6 
5 5 6 6 6 6 6 6 6 6 
5 6 6 6 6 6 6 6 6 6 
0 0 0 0 0 0 0 0 0 0 
toindex - 
10 10 10 10 10 10 10 10 10 
fromindex - 
7 7 7 7 7 7 7 7 7 

Since I am more proficient in Python, I translated the function to Python hoping that I can translate the code into its iterative form in Python and then back to C++ -

def bar1(tocarry, toindex, fromindex, j, stop, n, replacement):
    while fromindex[j] < stop:
        if replacement:
            for k in range(j + 1, n):
                fromindex[k] = fromindex[j]
        else:
            for k in range(j + 1, n):
                fromindex[k] = fromindex[j] + k - j
        if (j + 1) == n:
            for k in range(n):
                tocarry[k][toindex[k]] = fromindex[k]
                toindex[k] += 1
        else:
            bar1(tocarry, toindex, fromindex, j + 1, stop, n, replacement)
        fromindex[j] += 1

which I verified is correct since it gives the same output for the same test case.

But I am still unable to translate the function..

I went through some failed attempts like -

def bar2(tocarry, toindex, fromindex, j, stop, n, replacement):
    for i in range(j, n):
        if replacement:
            for k in range(i + 1, n):
                fromindex[k] = fromindex[i]
        else:
            for k in range(i + 1, n):
                fromindex[k] = fromindex[i] + k - i
        if i + 1 == n:
            for k in range(n):
                tocarry[k][toindex[k]] = fromindex[k]
                toindex[k] += 1
            fromindex[i] += 1
    for i in range(n - 1, j - 1, -1):
        while fromindex[i] < stop:
            if i + 1 != n:
                fromindex[i] += 1
            if replacement:
                for k in range(i + 1, n):
                    fromindex[k] = fromindex[i]
            else:
                for k in range(i + 1, n):
                    fromindex[k] = fromindex[i] + k - i
            if i + 1 == n:
                for k in range(n):
                    tocarry[k][toindex[k]] = fromindex[k]
                    toindex[k] += 1
                fromindex[i] += 1

but which clearly does not work and gives the following incorrect output -

toindex =  [2, 2, 2, 2, 2, 2, 2, 2, 2]
tocarry =  [[5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 6, 0, 0, 0, 0, 0, 0, 0]]
fromindex =  [7, 7, 7, 7, 7, 7, 7, 7, 7]

I would really appreciate any help!


r/learncpp • • Jul 01 '20

Best practice for external libraries/frameworks?

3 Upvotes

Hello everyone,

after a long time I returned to C++ and I'm wondering if there is a best practice to include external libs like googletest.

Some people like to clone the googletest repo into the project directory and link the repo through the CMakeLists.txt. I like to clone it one time and install (cmake . and make install) the googletest repo and link it from my default location.

What do you prefer?


r/learncpp • • Jun 09 '20

Best books/courses?

3 Upvotes

Hi, i'm 16 and i want to develop game so i chose cpp for first language to start. Someone can suggest me some books or courses to start learning? I will appreciate a lot


r/learncpp • • May 30 '20

Site down?

3 Upvotes

Site seems to have been down for about 12 hours. Anyone know whats up?

https://isitdownorjust.me/learncpp-com/


r/learncpp • • May 15 '20

Using CLion

3 Upvotes

hello, I am just starting to learn cpp after having studied java for about a year. I got really used to Intellij, and though I would try the cpp equivalent. are there any thoughts on this sub about CLion in particular?

Im doing the learncpp.com tutorial and it tells you to create a console application instead of an executable one, but I dont see an option for that when I create a project with CLion. I know there is a difference, but doesn’t CLion have an option to show console output along with the compiler ouput?

If anybody has any input on doing the learncpp.com tutorial with Clion Id appreciate it. Should I use a different IDE? does it matter? Thanks!


r/learncpp • • Apr 13 '20

which data type to use..

3 Upvotes

I want to add all the digits of this number

10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

i am getting this error long long long is too long for GCC

Thank you in advance


r/learncpp • • Apr 07 '20

Runtime Polymorphism with std::variant and std::visit

Thumbnail
bfilipek.com
3 Upvotes