lainchan / λ

C++ thread

Lukasiewicz · 2017-04-13 04:07
A general for all things C++. Discuss, ask questions, talk about or share your C++ projects here.
John Peters, You Know, The Farmer · 2017-04-13 17:58
So in Lainman's terms, what's new in C++17? I looked at a potential timeline of the direction of C++, and as a sort of novice programmer, I'm kind of excited for the development of a std:: 2-D graphics library library
Turner · 2017-04-13 19:42
I already posted this in the beginner's thread, but I think I might have more luck with it here: Could someone recommend an open-source project that has 1. Well-written, idiomatic C++ code that would be good for a beginner to learn from; something that you would consider a benchmark in code quality for C++ 2. Good design 3. Good documentation
John Titor · 2017-04-13 19:57
>>156 Wouldn't LLVM qualify for this? A compiler built on LLVM would also work in most cases.
Hong, Guil Dong · 2017-04-14 12:21
>>156 >>157 Second for LLVM source, added benefit of learning compiler design.
Nguoi La · 2017-04-14 21:51
>>145 >what's new in C++17 https://isocpp.org/files/papers/p0636r0.html
SHODAN · 2017-04-14 22:24
>>261 Most notable: - Guaranteed copy elision - Stricter order of expression evaluation - Fold expressions - Class template argument deduction - Constexpr if - Selection statements with initializer - Structured bindings - Filesystem library - Parallel algorithms - std::string_view - std::variant Though there's a lot of other good stuff.
list · 2017-04-15 00:00
>>262 >fold expressions >constexpr if >structured bindings >filesystem library >parallell algorithms C++ gets better with every version tbh
The Oracle · 2017-04-15 07:18
>>145 >>261 >Class template argument deduction A major, major win for readability. I cannot overstate how great this is. >Guaranteed copy elision And a pretty major win for both performance and code simplicity. >Attribute [[fallthrough]] >Attribute [[maybe_unused]] >Attribute [[nodiscard]] Friendly little changes. The first two will help reduce noise from compiler outputs. >A byte type Another little change, but the distinction is much needed. >clamp >Searcher functors >Splicing maps and sets I've been greatly missing the first two. I imagine one day soon I'll find myself missing the third as well. >Single-argument static_assert I'm not sure why static_assert required an output message in the first place. Repeating the asserted expression is obviously redundant and for the any other message: if you need to document your documentation, you're probably doing something wrong. I'm looking at you, OpenCV. Check my inputs with assertions and tell me about those. If assertions are throwing deeper down, the implementation is flawed. If something exceptional happens, tell me with an exception. std::logic_error exists for a reason. Do not scream at me about variables I've never seen before. >Tuple apply >Construction from tuples This addition is going to be really nice in combination with template argument deduction. >Attributes in namespaces and enumerators I don't thinks it's a big change, but I can see it being very useful going forward. >A variadic version of lock_guard called scoped_lock A strict improvement of lock_guard, making more concise and readable code in combination with template argument deduction. What's not to love? >shared_ptr for arrays This should remove a good deal of the fuarrrkery involved with using plain C libraries. Good riddance to potential leaks and typing acrobatics. The filesystem library is obviously an excellent addition. What I'm really hoping to see soon, though, is the currently experimental standard networking library. I share the concern some feel about whether something like io2d should be part of the standard. I say that as someone who writes code mostly relating to computer graphics and who would love to have better tools and more generic interfaces. One of the two areas so far where I've chosen to use Go over C++ is for graphics because Go has support for it in the standard library. The other is, naturally, the World Wide Web. But that's Go's library. The C++ stdlib is a very different beast with very different goals. Graphics, despite being almost universal, may be something better left to third parties.
Random · 2017-04-15 09:15
>>291 >The filesystem library is obviously an excellent addition. It's probably going to use Boost's implementation, right?
vector · 2017-04-15 19:19
>>301 It is an adoption of the Boost library. The networking library is also an adoption of boost::asio.
Dozer · 2017-04-16 02:48
>>301 >>321 Boost is already basically an extended version of the stdlib.
drop · 2017-04-17 16:26
>>365 >>382 Maybe somebody here can help me with this. I've clearly misunderstood how references work.
Zero Cool · 2017-05-04 09:43
I really, really, really wish C++ could add concepts sooner than later. They are far more important than any facelift feature or new ugly initialization syntax. The fact that the committee has delayed them for so long is frankly criminal.
Motoko Kusanagi · 2017-05-06 03:52
>>38 > share your C++ projects here I forked some abandoned github project that converts maps from Reflex to id Tech 3 format. https://git.teknik.io/scuti/reflex2q3 It had one issue on its page, but there were a lot of undocumented bugs. And initially it, being a Visual Studio project, didn't compile at all on g++. Right now really happy to see the geometry cleanly and correctly ported.
Unnamed · 2017-05-06 03:53
>>952 A before and after, by the way.
Cypher · 2017-05-06 08:00
>>952 fuarrrk I really loved reflex but no Linux support killed it for me, I still play cpma on ioquake3 though. would love to see xy2 on cpma. keep it up man would love to see this come to light.
Fred Nurk · 2017-05-11 01:19
Has anyone read Beginning C++ Through Game Development? I'm wondering if a book focused on a single domain like this might leave me hamstrung in other domains. Game development is a major interest of mine, but I wouldn't want to pigeonhole myself too strongly.
Pris · 2017-06-14 17:21
>>1063 It is actually quite good, I read it with the same mindset as yours but it was actually very good. The "game dev" is actually just examples, the core concepts being the usual. But I'd recommend "C++ primer"(NOT "C primer Plus").
progn · 2017-06-14 18:43
>>1063 I wouldnt recommend c++ as a gamedev, in contrast to being an engine dev. Yes those are quite different sides and an actual reality nowdays. Using an already made engine saves you so much time. >>952 More details plox!
Leto Atreides I · 2017-07-12 07:44
>>1798 As a (late) follow up. The new major change to the program that users would notice is the addition of entity translations from Reflex to other games. Meaning if you wanted to port over a map, you wouldn't need to place back every item and trigger and worry about accurately doing so. For the gameplay related pickup items, the translations are determined by a file since different games have different entity tags. The next addition, which people are less to notice or attribute as significant, is the texture definition converted as opposed to placeholders in the output. Unlikely to notice because Reflex doesn't conventionally have textures and instead has colors and lightmaps(?) applied to faces. The color is expressed in ARGB, but the .material's format hasn't been investigated (not planning to). In the screenshot you can see the surfaces in-editor aren't flat blue anymore, and instead are actually "SHADER NOT FOUND". Some general bugs have been fixed and the converter is observed to work with both Reflex's map version 8 (reason behind the fork) and version 6 (the outdated format that the original converter only worked with).
Hong, Guil Dong · 2017-07-12 08:02
>>2277 An example of a quickly compiled map from Reflex in Xonotic. To go back to the topic of C++. The original project uses C++11 and the additions, etc continue using C++11 features; almost only the range-based for statements (iterating through plane points, faces, and entities) with some cases of auto in the entity converter component.
J.C. Denton · 2017-07-12 15:55
>>1063
FILLER · 2017-07-19 13:51
What is a reasonable way to handle errors in destructors? I'd like to just clean up and then terminate the program by returning from main, but I'm not sure how to get there without throwing an exception out of the destructor.
Hitomi · 2017-07-19 18:05
>>2457 Maybe use longjmp()?
Donna Hawthorne · 2017-07-19 20:06
>>2457 Can you describe your situation in a little more detail? What's producing the error? What type of resource are you handling? If you're absolutely sure you want to nuke the entire program when this component fails, you can call std::exit() (preferably with logging). Otherwise, I would recommend creating a throwing release function that the object's user can handle and letting the actual destructor ignore the error (preferably with logging). This is the approach taken in the standard library, or at least with certain parts like file I/O.
Bob Arctor · 2017-07-19 22:17
>>2478 I'm new to all of this, so I'm not sure how best to explain it. I'm learning to use libsndfile and portaudio, and one of the things I'd like to do is to have a class to go around both libraries, so that I could use the class to play an audio file. With the way I've got it now, the destructor needs to close the portaudio stream, close the file, and then terminate portaudio itself. All of these things can return an error value. I think I'll probably go with your latter suggestion
John Titor · 2017-08-12 14:01
>>145 >I'm kind of excited for the development of a std:: 2-D graphics library library So was I. My life would very likely have gone in an entirely different direction if the Committee was farsighted enough to include a minimal graphics library from the beginning. As things were irl it was far too difficult to get everything up and working right as a beginner trying to create my first game in C++ I eventually abandoned hope and left the language. As an adult I've returned to it and today could make a game if I wanted to, but back when it really counted (as far as my future direction in life) I couldn't. I honestly doubt the Committee will ever capitulate to Sutter's push and include the graphics TS. I hope they prove me wrong.
Judge Fang · 2017-12-05 13:03
How do I begin learning the Boost Library?
Sabo Engle · 2017-12-06 11:08
Why is C++ such a clusterfuck? I love it as a language, but it is a fuarrrking mess of different paradigms.
Technician · 2017-12-06 18:49
>>5439 Backwards compatibility. Nothing ever gets deprecated from the standard.
Neuromancer · 2017-12-08 09:42
>>265 I'm holding off on that until modules and concepts are an official thing.
Ein · 2017-12-08 09:45
>>5439 Because it's defined by a standards body that is an assortment of men that represent the real-world interests of big companies and the problems they actually face, not some academic or proprietary ivory tower. This multi-paradigm heterogeneity is a strength, not a weakness. Welcome to the real world anon. You want something simple and unified? Try Scratch to be honest.
Nobody special · 2017-12-08 09:50
>>5410 Probably by picking a single, specific, library and trying to work through the example programs and mastering just that one thing. This should let you ease into Boost's philosophy slowly and become adapted to the way they do things. Trying to take it all in at once is definitely a mistake. Even the Committee has few who know every nook and cranny of Boost.
Technician · 2017-12-08 09:57
Why hasn't anyone in this thread already linked this? It's arguably the single greatest freshman textbook on learning how to program bar none. http://www.stroustrup.com/Programming/
Ivan Petrov · 2017-12-08 18:18
>>5482 I wouldn't go that far, but it is a really high-quality book. Anyone who is somewhat new to programming and wants to use C++ for whatever reason should get it imho.
The Fin · 2017-12-08 23:35
>>5486 >I wouldn't go that far I realize that there's no 'cookie cutter one size fits all' when it comes to something as creative as software development, but name me a single other freshman programming textbook that is better suited to preparing any serious students for the real world of software programming? In any language? It stands apart at this point.
H.R. Giger · 2017-12-09 00:10
This is a bit of a novice question, but I'll ask it anyway. I am new to computer science. In fact, this is my first semester. I went in with no prior knowledge, but I fell in love with programming during this semester and I have always been a huge fan of mathematics and physics, which is one of the reasons I got into this field. I started learning C++ using this amazing website learncpp.com I am liking it a lot, but everyone at my university who has more experience than me in programming is advising me against learning it. They're saying things such as: > you need to have a specific reason to learn it. > it will die soon > you will mostly be working with legacy code if you become a C++ developer. > you should focus on C and Python instead. > learning C++ without a good reason to do so is crazy > C++ requires you to be extremely talented; otherwise, you'll write really bad code. Are they right? Should I stop learning C++ and move on to another language? I don't have any specific goals or reasons for learning C++. I just chose it because I heard that it was a very powerful language and because I loved C a lot, which is what we took in our introduction to programming course. I am grateful for any answers! :)
Hououin Kyouma · 2017-12-09 00:41
>>5482 Is that book really that great? Read the first chapter or two before and it seemed a bit ghetto. Also went to grad school at A&M always meant to go look Stroustrup up and talk to him, but never got around to it.
Mario Rossi · 2017-12-09 02:50
>>5498 The first few chapters are a bit basic and assume no previous programming experience. The latter chapters are really, really good. Like for example the one where he explains the issues related with embedded and real-time programming such as memory fragmentation.
vector · 2017-12-09 03:02
>>5499 Ah that's probably the problem, the beginning part just didn't really hold my attention so I moved on to different things. Might give it another go if I get back to having a desire to learn C++.
null · 2017-12-09 06:53
>>5494 I would say you should go find some answers to these objections on your own at the superfaq and stroustrup's own list of C++ applications. C++ is at the heart of many many domains doing seriously heavy lifting in computing. If you are really serious about learning hardcore development skills for domains like robotics, aerospace, graphics, HPC, telecoms, or financial trading you can't go wrong with the language. And the fact it's an ISO standard practically guarantees the language itself will never disappear from the field. BTW, the number is C++ devs is growing atm, not shrinking. Maybe you should also consider finding some other friends at school anon. https://isocpp.org/faq
⍕ · 2017-12-09 10:54
>>5507 Thank you so much for your answer. I also wasn't aware that this super FAQ existed; it is a wonderful resource. What these people were saying to me really discouraged me from learning, but now I'm really pumped up to learn again thanks to your answer and the FAQ you linked to. <3
Liet Kynes · 2017-12-09 13:05
>>5509 You're welcome I've developed with C++ for more than a decade now and I can always find good paying work. I've programmed with the language in these areas that I can think of just off the top of my head: broadcasting (radio), small and medium-sized business applications, vidya, film, aerospace, and gpu-based image processing. Currently I'm in school again working on my maths before I venture into the AI and robotics fields using it -- both are heavily demanding C++ devs right now. Also, please don't ignore my basic advice for undergrads that I gave here anon: >>5482 >>5493
Meddler · 2017-12-09 18:32
>>5510 Thank you for the recommendation. I will check it out! :)
queue · 2017-12-09 18:48
>>5494 Some of their advice has merit but most of it sounds wrong to me. Lots of big projects use C++, but more importantly than that, C++ is one of the most multi-paradigm languages you can find, behind maybe lisp, etc. Because of that, if you decide to jump to another language, it will be easier because you've used that model before, like if someone learned in Python and suddenly had to switch to Java it would be painful, but from C++ to Java or from C++ to Python are both very easy because C++ incorporates both of their styles, technologies, language features, etc... C++ also has a lot of amazing concepts like templates, move semantics, lambdas, smart pointers, etc.. that make it fun to program in. I don't personally find C++ to be my favorite language, but if you enjoy it then learn it and the reasons they're citing are mostly garbage. "it will die soon" no it won't, "you will mostly be working on legacy code" maybe, but a lot of people say the same thing about C, "you should focus on C and python" if you know C++ you know most of C and have more than enough skills to pick up python very quickly, "C++ requires you to be extremely talented" true but talented compared to java brainlets, which isn't saying much. However I absolutely have to recommend that you read Effective Modern C++. It will teach you way more than any other textbook about the language features that make C++ different and also easier (and more fun) to program in. If you enjoy it, I would also recommend 21st Century C, because it's quite similar, and goes over more tips and tricks than I can count about how to make it easier and more fun to write (C, not C++) code.
cond · 2017-12-09 21:50
>>5515 Strong agree on Effective Modern C++.
Nobody important · 2017-12-09 21:50
>>5515 Thank you very much for the explanation and for the book recommendations. Effective Modern C++ was already on my list of books that I want to read when I get a better idea of the language and programming in general. I also have a list of intermediate and advanced books that I would like to read, which I got from a question on stackoverflow. https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list
bit · 2017-12-10 01:34
>>5513 You're welcome. >>5515 That is a great book, arguably Meyer's best one. However it's hardly a beginner's book. The Super FAQ lists it in the 'Morality Guides' category and I'd say I have to agree overall. For experienced devs I'd say it's greatest value is helping to understand in detail some of the great new features in Modern C++14, and some of the gotchas involved (a number of which have already been corrected in C++17). Good insightful post anon. Can confirm everything you said. For my part I would say that Tour++ is the single best starter book for any experienced developers (or even beginners once they work through PPP2 above) looking into Modern C++. It's short, to the point and covers a broad swath of material in just 180 pgs. I own basically every important C & C++ book out there, but this is one I keep very handy. Highly recommended. http://www.stroustrup.com/Tour.html
The Plague · 2017-12-10 01:44
>>5520 One thing I forgot to mention that may put my post in context: This book is the K&R of C++.
push · 2017-12-10 20:40
On the topic of FAQs, I'm interested in reading what you all think of the C++ FQA: http://yosefk.com/c++fqa/ It makes C++ seem nightmarish and this rabbit hole is part of why I've avoided learning the language, but I'm wondering what C++ programmers have to write on it.
Moore · 2017-12-14 02:58
>>5533 b8?
Joe Bloggs · 2017-12-14 09:03
>>5533 The creator of C++ has a famous saying >There are 2 types of programming languages in the world, those that people bitch about and those that nobody uses
Meddler · 2017-12-14 09:22
>>5648 I'm going back to c++ after experience in other languages. What is most annoying at first sight are the layers of added functionalities in the language syntax and semantics, because it seems each of them was added so that coders could be more « effective », but they add a clusterfuck of rule of thumb that you have to learn through practice alone.
藤原純一 · 2017-12-14 18:56
>>5650 >it seems each of them was added so that coders could be more « effective » The primary design goal of C++ is zero cost abstractions. That means performance is more important than cognitive load on developers. If you want easy building blocks a toddler can stick together with dogsoykaf performance then go use Python.
Ivan Petrov · 2017-12-15 03:09
Okay so currently I'm learning Common Lisp (and programming I guess, since despite having "programmed" my entire fuarrrking life I'm pretty soykaf at it and have only ever just sorta fuarrrked around until soykaf worked) but I get distracted/bored easily if I focus on a single thing, and Common Lisp isn't exactly a hugely popular language, so I'm thinking of working on C++ too since it seems all around much more useful, especially if I want to work on open source projects and such, and for the various domains I'm interested in which are things like numerical simulations, graphics, AI/Machine learning, and so on, all computationally intensive stuff. So point is, how to best go about learning C++ and how to properly program but also develop actual software? Going to be going through Programming: Principles and Practice using C++ as suggested previously in this thread, and also looking through source code (such as LLVM also suggested in this thread). What else would be good? Should I look into the KDE source code? I want to learn Qt (probably) alongside C++ at some point, and potentially contribute to a big project such as KDE. Is this even feasible? Is it worth it to learn Qt dev?
Naomi Nascimento · 2017-12-15 03:47
>>5657 >That means performance is more important than cognitive load on developers. This. And with the move back to big iron and big data, the cost pendulum has swung back towards runtime perf, if for no other reason than electricity bills. Dev maintenance cost is much less of a factor now (percentage wise) than it has been in the past. C++ is king in this area of nice abstraction + runtime performance. The source of this is again, men on the Committee represent real-world engineering concerns of big entities with multi-billion line codebases.
Project 2501 · 2017-12-15 06:26
>>5665 >LLVM >KDE It's traditional to walk before you run. PPP2 will be more than enough for you for now anon. Finish that 1200+ pages (with the exercises ofc) and then come back to us with more questions if you have them still alright?
Ivan Horvat · 2017-12-15 09:36
>>5665 I'm not sure if KDE is particularly renowned for their code quality. The best open source projects to contribute to are ones you actually use everyday. If KDE is your full time desktop environment then that would be a good project to get involved in. I do occasionally see jobs for Qt developers. Usually embedded/IoT devices running embedded Linux have user interfaces written in Qt.
Lady 3Jane.. · 2017-12-15 17:17
>>5644 It's not. I'm genuinely curious. >>5648 >The creator of C++ has a famous saying >>There are 2 types of programming languages in the world, those that people bitch about and those that nobody uses The issue is that's roughly what you'd expect someone to say if the language they designed is truly like the FQA describes. The C language has its undefined behavior and obsessions; Lisp is regularly denounced as academic, useless, or only useful for certain things; Perl is called line noise, among others; I'm merely wondering what actual C++ programmers think, especially because I oddly enough see little varied criticism of the language.
Liet Kynes · 2017-12-15 19:18
>>5671 Yeah yeah I know lol, will do. Quick question though... How TF do I compile the examples from PPP? I'm literally on the first example of the first chapter, doing the basic hello world, but the std_lib_facilities.h file is causing me problems. I'm on whatever the latest OSX is and using the -std=c++11 flag fixed some things only to cause other errors, adding -stdlib=libc++ helped some but got another error, since apparently it doesn't include forward_list? using -stdlib=libstdc++ causes a whole host of other linker issues... wtf why is this such a pain in the ass? Why not just use the standard include files instead of this soykaf?
Jim Hilger · 2017-12-15 19:36
>>5687 Sounds like you are using a C compiler instead of a C++ compiler. Like running gcc instead of g++ or something. Post the whole command.
list · 2017-12-15 21:03
>>5688 I'm using the command 'cc' which invokes clang on OSX. But damn you're right, using clang++ instead of cc worked, with options std=c++11 stdlib=libc++. Still got a couple warnings though, does this stuff matter? Anyway, thanks!
cond · 2017-12-16 04:36
Newbie here, i'm struggling on how to start learning C++, where should i start? Which skills do i have to upgrade to achieve decent programming level? I'm currently on pseudocode stage
Cereal Killer · 2017-12-16 09:19
>>5690 >Still got a couple warnings though, does this stuff matter? Did you declare i as an unsigned type? The warning is telling you that i<0 is always going to be false because i is unsigned, which means it will always be non-negative. Since you're checking for it to be less than 0, I'm guessing you want to drop the unsigned bit in the declaration.
list · 2017-12-16 14:30
>>5690 No problem. Every C++ programmer has done that at some point.
John Rain · 2017-12-16 14:43
Hello, lainons. I am working on my first programming project, due I have many files it is getting somewhat messy. I want to organize the code in folders, I already created all of them but now I don't know how to include my headers. I used to do it this way: #include "Cola.h" #include "Dao.h" Now, Cola.h and Dao.h are not in the same directory as the main file I tried doing this: #include "./Cola/Cola.h" #include "./Dao/Dao.h" I get this error: In file included from main.cpp:11:0: ./Dao/Dao.h:10:18: fatal error: Cola.h: The directory doesn't exists. compilation terminated. What do I have to do? I am using this makefile cc = g++ main: main.o Dao.o Cola.o Nodo.o $(cc) -Wall -I/usr/include/cppconn -o main main.o Dao.o Cola.o Nodo.o -L/usr/lib -lmysqlcppconn
Drano · 2017-12-16 16:01
>>5710 Those aren't from my program, it was just a simple hello world. They're from somewhere in the linked libraries I guess. New problem, I'm getting garbage output and not sure why: #include "../std_lib_facilities.h" int square (int n) { for (int x=1;x<n;++x){ n += n; } return n; } int main() { for (int i=0;i<100;++i){ cout << i << '\t' << square(i) << '\n'; } } Once I get to i=2 I start getting large negative numbers, but as far as I can tell I initialized everything properly. 'i' always has a correct value, 'x' gets initialized again in the loop every time, and 'n' should be set to the correct value every time the function is called, so it doesn't matter what I leave it at, right?
Nell · 2017-12-16 16:01
>>5712 Simply do #include "Cola.h" and use -I to tell the compiler what directory the header file is in. This is standard practice because different Operating Systems will keep header files in different directories and people shouldn't have to change the #include statements in your source code, they should change the include path in your Makefile. $(CXX) -Wall -I/usr/include/cppconn -I ./Cola -I ./Doa -o main main.o Dao.o Cola.o Nodo.o -L/usr/lib -lmysqlcppconn Also, $CXX is the standard variable name for the C++ compiler. $CC is the C compiler (and $CPP is the C Preprocessor).
The Oracle · 2017-12-16 16:02
>>5713 fuarrrk, never mind, I see it. It's because of n += n, I'm not incrementing by the original value of 'n' so it's growing huge. Don't know how I missed that.
array · 2017-12-16 16:04
>>5715 Well hell, not only the n += n but since I'm comparing 'x' to the growing value of 'n' my loop gets crazy too. What a train wreck lol.
McCarthy · 2017-12-16 16:14
>>5713 for (int x=1; x < n; ++x) { n += n; } Be careful, because the value of n decides when the loop will stop, and you increase the value of n everytime the loop executes. So x will always be smaller than n until n reaches its maximum value and overflows, that's where the negative numbers are coming from. If you want the loop to execute n times you need to keep the value of n the same, and use a different variable for creating the result.
⍕ · 2017-12-16 22:12
>>5714 It didn't work. Same error, the compiler does not find Cola.h file
McCarthy · 2017-12-17 04:07
>>5685 >especially because I oddly enough see little varied criticism of the language. Then you simply aren't paying attention to the men that matter. We all know there are a ton of warts with the language, mostly as holdover issues from backwards compatibility with C. That's what things like the Core Guidelines project is about: avoiding the dark corners where bugs lie. The reason we use it in spite of the issues is that it simply brings the strongest set of positives to the table for the kinds of projects we work on. Want to hear some real pros in the language bitch about it instead of some butthurt dweeb? Watch the videos here. I'd recommend all of the Committee member's videos first because a) they matter most, and b) no one else collectively knows all the language's foibles better. https://www.youtube.com/user/CppCon/playlists
Terzibashjian · 2017-12-17 09:16
>>5724 I'm sorry about that $(CXX) -Wall -I/usr/include/cppconn -I ./Cola -I ./Doa -o main main.o Dao.o Cola.o Nodo.o -L/usr/lib -lmysqlcppconn This line is only linking the object files together. You need to put the -I parts in the rule that compiles the .c source files into .o object files.
Ishikura "Tatsu" Tatsuhiko · 2017-12-17 11:50
>>5666 >And with the move back to big iron and big data 'big iron' is slang for mainframes, we stopped using mainframes over 40 years ago, we certainly arent 'moving back' to them however many companies have chosen to continue to support these legacy systems as it is too expensive to rebuild everything on modern systems (hence the choice to continue is confused with 'moving back'). Big Data has nothing to do with 'big iron' and everything to do with thousands of server racks in football field sized server farms. >the cost pendulum has swung back towards runtime perf, if for no other reason than electricity bills. quite the opposite, Moores law ended, a 10% increase in runtime performance means almost nothing when scaling across thousands of servers >Dev maintenance cost is much less of a factor now (percentage wise) than it has been in the past. really, why dont you do a cost analysis on Google's employee salary costs (over 50,000 programmers all making over $100k a year) vs electricity costs of running their servers >C++ is king in this area of nice abstraction + runtime performance. C++ is the court jester of nice abstractions. And again, a 10% increase in runtime performance doesnt mean soykaf on distributed systems >The source of this is again, men on the Committee represent real-world engineering concerns of big entities with multi-billion line codebases. The source of this is men on the C++ committee with multibillion dollar legacy codebases that they cant afford to have break
stack · 2017-12-17 14:44
>>5739 Are you sure? In my original makefile I didn't specified any source files and it worked properly.
BloodCat · 2017-12-17 18:38
>>5744 What I don't understand is why don't they freeze C++ development and start a new language very close and carefully designed, that can use c++ libraries.
Undisclosed · 2017-12-17 20:13
>>5747 Because it'd fail
Ivan Petrov · 2017-12-19 06:44
>>5744 >a 10% increase in runtime performance means almost nothing when scaling across thousands of servers >a 10% increase in runtime performance doesnt mean soykaf on distributed systems 1) Where does that 10% figure come from? 2) What exactly are you basing your "means almost nothing when scaling" claim on? If your argument is that costs related to inter-server communication overwhelm savings from application performance, then surely, if the performance of a local application increases, the need to perform the computation in a distributed fashion (therefore, to communicate between server) decreases. If this isn't what you meant, then you're out of your mind. Moore's law ending is EXACTLY the reason performance matters more than ever. Two decades ago: "Who cares if my software is slow bloated crap? Next year's computers will be able to handle it just fine." Today: "Uh oh my nice-looking garbage-collected abstraction-filled soykafcode runs like soykaf. Better switch to C++." Throwing more hardware at a problem can work (sometimes, and partially; see Amdahl's law), but for anyone serious, it's a last resort solution. Also, parallelization doesn't help with low latency applications.
Erik Johansson · 2017-12-19 07:08
>>5758 >1) Where does that 10% figure come from? nowhere, I am giving you a random hypothetical >2) What exactly are you basing your "means almost nothing when scaling" claim on? If your argument is that costs related to inter-server communication overwhelm savings from application performance, then surely, if the performance of a local application increases, the need to perform the computation in a distributed fashion (therefore, to communicate between server) decreases. Im not even going to waste my time trying to figure out how you could be so wrong, a servers main purpose is to find, organize and retrieve data, so on a distributed server system almost all this work is done parallel. If you cant see that, then there is nothing more that I can say, Im just going to assume youre playing dumb because you really dont have any argument to offer.
Fred Nurk · 2017-12-19 07:28
>>5759 >I am giving you a random hypothetical A dumb hypothetical that I have no reason to accept. Compared to other "nicer", often garbage-collected languages relative gains from using C++ can be way higher. > a servers main purpose is to find, organize and retrieve data A server's main purpose is to perform a computation (any computation, really) at the request of a client. What you're talking about is a database. Not every server is a database. I would also argue that a database would benefit from high performance code. >a distributed server system almost all this work is done parallel Yes, by definition of being a "distributed server system", things are done in parallel. Good job. My point is that you can use a performance increase to make your system less distributed, and benefit from that. >Im not even going to waste my time trying to figure out how you could be so wrong, >If you cant see that, then there is nothing more that I can say, Im just going to assume youre playing dumb because you really dont have any argument to offer. lol, you don't need to be so aggressively pretentious. Go read about Amdahl's law and communication overheads. Or go consider how distributed/parallel computing is worthless for low latency applications.
Erik Johansson · 2017-12-19 07:45
>>5760 >A dumb hypothetical that I have no reason to accept. Compared to other "nicer", often garbage-collected languages relative gains from using C++ can be way higher. benchmarks are available for anyone to make up their own mind >A server's main purpose is to perform a computation (any computation, really) at the request of a client. What you're talking about is a database. Not every server is a database. I would also argue that a database would benefit from high performance code. the kind of distributed server systems that a company like Google uses doesnt fit into your junior level idea of what a database is >My point is that you can use a performance increase to make your system less distributed, and benefit from that. this just shows that youre living in moms basement, no increase in runtime performance will decrease latency, I/O is a sunk cost that you can only decrease with improved paralelism >Go read about Amdahl's law and communication overheads. servers are inherently paralyzable, Amdahl's law just measures the ability to increase speed by parallelizing something >Or go consider how distributed/parallel computing is worthless for low latency applications. this is the last time I am going to respond to you, youre just blowing out bullsoykaf hoping its going to cover how obviously wrong you are. I/O whether its cross server or hard drive reads have inherently high latency, the vast majority of time spent on a distributed server server is doing data reads and cross server I/O
Dox · 2017-12-19 08:55
>>5761 >the kind of distributed server systems that a company like Google uses doesnt fit into your junior level idea of what a database is >psshh, what the guys at Google are doing is just beyond your comprehension, kiddo. just trust me, I know my soykaf Very persuasive. Google uses distributed server systems because they need to, not because it's a magically perfect solution, and it doesn't change the fact that each individual database server would benefit from higher performance. >no increase in runtime performance will decrease latency What the fuarrrk. An efficient server that routes information on a network won't have a lower transfer latency than a slow one? Well then, I guess maybe we should start programming routers completely in Ruby. >I/O is a sunk cost that you can only decrease with improved paralelism "improved" parallelism? Could you be more vague? Also there are hard performance limits to communication from a distance, obviously (for example, the speed of light). >servers are inherently paralyzable Not necessarily. Depends what tasks they do. >Amdahl's law just measures the ability to increase speed by parallelizing something Amdahl's law says that, as the non-parallel fraction of a program increases (e.g. communication overhead), the returns from an increase in parallelization diminish faster. Conversely, you can get more benefits if the parallel fraction is greater (e.g. less communication and more local work (hopefully done efficiently) on each server). Glad I could help. >I/O whether its cross server or hard drive reads have inherently high latency, the vast majority of time spent on a distributed server server is doing data reads and cross server I/O Do you even realize that you're supporting my general point? You use distributed server systems because you need to. The higher the performance of your programs, the more work you can potentially do locally, and the less you waste time communicating. And even when communication is necessary, minimizing the response latency of the application can be crucial (for instance, it's no coincidence that C++ is used in high-frequency trading).
array · 2017-12-19 09:11
>>5762 >The higher the performance of your programs, the more work you can potentially do locally, and the less you waste time communicating. except when that work is finding/filtering information distributed across hundreds of servers watch a C++ video about how Moores Law is over and high memory latency is the bottleneck that can only be solved with concurrency: https://www.youtube.com/watch?v=SpLkejkqtSQ&t=172s
Hacker · 2017-12-19 09:28
>>5763 >except when that work is finding/filtering information distributed across hundreds of servers Sure, I would agree if passing information around was the only thing Google was doing with its servers. As it happens, they also do plenty of pure computation. You can bet they want to squeeze every drop of performance out of each individual machine when running their neural networks (or generally extracting and analyzing information). Herb is a cool dude, will watch the video later.
Six · 2018-01-11 10:06
I'd be interested to know what lainons think of the new C++ metaclass proposal: https://herbsutter.files.wordpress.com/2017/07/p0707r1.pdf https://www.youtube.com/watch?v=6nsyX37nsRs Metaclasses with compile-time constraints in a statically typed language is insanely interesting. I can't think of any other language that has this.
Trinity · 2018-01-11 13:02
>>6079 https://forum.dlang.org/thread/kglnxqbcugerhynngewp@forum.dlang.org?page=1
pop · 2018-01-12 03:16
Just wanna share this this thing i'm making: https://github.com/easymodo/qimgv It's an image viewer written with C++ / Qt 5. Supports webm playback via libmpv. Nothing extraordinary programming-wise but maybe you'll like it. Here is a quick video overview: https://www.youtube.com/watch?v=AODRGCRPCpw
Hitomi · 2018-01-16 19:46
how do i learn making cool stuff in C++. literally a noob in programming but how do i learn making small games with engines or text based games.
Lord Nikon · 2018-01-17 00:23
>>6228 If you are a noob in c++ then try sfml2 library and creaate some games. I've been addicted to it when I was starting my journey with programming.
Anonymous · 2018-01-17 00:25
>>6228 small revision If I remember correctly I've started with sfml 1.6. Now there is 2.4.2 version which is way better. If I ever learn lots of $ via programming then I'm gonna send some of it to Laurent Gomila and other folks from sfml team for such an awesome job
Iverson · 2018-01-23 07:23
I wrote a program that downloads files from lainchan (and 4chan and wizchan) after reading >>6041 reply. This was my first time using the Boost Libraries so the code might be a bit messy. Enjoy, and please recommend improvements. Link: https://github.com/himnish/lain-get
CerealKiller · 2018-01-23 23:26
>>5709 Youtube CaveOfProgramming. The guy is pretty damb good at teaching it.
Iverson · 2018-01-24 07:02
>>5841 >>5878 I have now decided that this tool would work best if it were a little program that used flat CSV files from ~/.config/chunkerchunks. Best model, I guess, would be to make a /bin/chunker which you could just call like ~$ chunker issue 'problem text' ~$ chunker solve 'solution text' I could do it with any language that supports CGI mode but then it depends on that language. Which is why I'm thinking a compiled binary would be better. Now, should I do it in C++ or Rust/Go?
vector · 2018-01-29 00:32
>>6385 Man, CGI is trivial -- just some environment variables on input and you write back headers and whatever content. About the only complex thing is handling forms with files. Maybe if you wanted FastCGI, that gets interesting.
Hitomi · 2018-01-30 13:49
>>6459 no I mean non-http CGI mode like using the script as an executable but telling the OS #!/usr/bin/langinterpreter in line one perhaps that's not CGI at all but you get what I mean lol btw I did decide on C++ and it took me a coupla days to properly parse command line arguments, I'll get back to it soon and will have you lainons review it
Leto Atreides I · 2018-01-30 14:45
>>6380 Thanks for the suggestion I appreciate it. https://www.youtube.com/playlist?list=PLmpc3xvYSk4wDCP5zjt2QQXe8-JGHa4Kt
Neo · 2018-02-10 15:32
>>6228 >or text based games NCurses is more or less a C library but has C++ bindings. Here's a very basic tutorial series that can probably get you on your feet as a beginner. https://www.youtube.com/playlist?list=PL2C01CC54638DD952
null · 2018-03-05 16:27
>>156 Any KDE project that's not currently abandoned.
Anamika · 2018-03-20 13:04
>>6110 I love this so much. I'm experiencing a renaissance in organization now that I'm freed from the damned file explorer when dealing imageboard related media. I really appreciate the darkly themed gui too.
Terzibashjian · 2018-03-20 17:56
>>6110 build fails with "error: ‘devicePixelRatioF’ was not declared in this scope float newMinScaleX = (float) width()*devicePixelRatioF() / mSourceSize.width();"
Joey · 2018-03-21 10:40
>>7398 You'll need Qt 5.6+
Mario Rossi · 2018-03-21 22:48
>>7401 I have 5.10
Junichi Fujiwara · 2018-03-23 15:13
someone here uses qt5? where are there good tutorials for simple GUIs using it?
fsociety · 2018-03-24 00:12
>>7442 honestly the built-in examples and the documentation (also available on the website) are pretty good as tutorials.
Meddler · 2018-04-22 13:58
Q. What is the fastest library for downloading a file e.g. an image from lainchan? I'm using libcurl now but it is quite slow. Can curl be made faster with any options?
Vasya Pupkin · 2018-04-24 16:53
>>1796 question. I've been reading primer plus, what's the problem with it?
SHODAN · 2018-05-04 21:19
I see a lot of stuff here, I'm sorry for asking to be spoonfed, but what is a good book for an introduction?, that isn't DRM protected trash.
queue · 2018-05-12 08:42
Hello, everyone! :) I'm sure that this question has been asked a lot, but I am not sure if I've found the solution to my situation. Also, not sure if it fits in this thread, so if it doesn't, please forgive me and please don't ban me. :3 I'm a beginner programmer; I started studying computer science and fell in love with it. I've only taken two programming courses: an introductory programming course where we learned C, and an object-oriented programming course where we learned about object-oriented programming conceptually and then learned and used Java for the practical lab sessions. As you can see, I don't have much experience, but I am really interested in learning C++ for many reasons. I've seen Accelerated C++ and C++ Premier being recommended on many sites, including here. I've read that C++ Premier is aimed more at beginners whereas Accelerated C++ is aimed more at people with programming knowledge, but I'm not sure which one to pick up. How advanced is Accelerated C++; would someone like me who has only 2 semesters of programming experience be able to keep up with it? Thank you for any and all answers! :)
Lord Nikon · 2018-05-12 12:54
Best library for creating a TUI in C++?
quote · 2018-05-12 13:04
>>8271 ncurses?
Armitage · 2018-05-14 04:17
>>8271 termbox perhaps? Simpler than ncurses, and is (I think) cross platform.
Mario Rossi · 2018-05-23 15:48
>>8185 learn how to use google, glitterboy. A good introduction is "Starting Out with C++", A good professional one is "Effective Modern C++" And I don't know what book would fall between these two. I want to ask for advice, because I've done the first book, but the second one makes no sense to me, I think theres supposed to be another one between them.
Haruyoshi · 2018-09-22 04:14
I am working on a system which would stream a linux terminal over an arduino network. So I am trying to create/interface with a terminal session. I looked at a python library called pyte, but even though I could do it in python, I kinda want to do this in C/C++, does anybody know some library for C++. I wouldn't really mind to imploment this part myself but I can't really find any documentation on creating and interacting with a terminal session.
Moore · 2018-10-06 17:53
what are you favourite c/c++ compilers for windows 10? (i am currently stuck with windows 10 for a while...) i refuse to use visual studio and i am not sure about viable alternatives
Guthrie · 2018-10-06 17:55
(OP) i know i could use gnu c++ compiler under cygwin, but i don't think that would be the most effective way (+ you know, i'd need binaries for windows :D ) also i meant visual c++ not studio, but i guess you get me
x<->y · 2018-10-10 12:55
>>10767 code blocks
Special Agent Bob · 2018-10-17 07:45
I just got a 2250 line error message from g++ compiling a 25 line program because i mistyped "mutable" in a lambda. This is crazy! To be fair the first few lines of a error dump stated where is the problem but still this is shocking to me how g++ can generate giberish error messages like this!
Haruyoshi · 2018-11-03 10:53
I just started learning C++, I'm watching a youtube tutorial and when I click build & run the console doesn't open.
Nero · 2018-11-03 11:06
>>11182 You probably haven't connected your compiler to Code Blocks yet. If you search it there are tutorials that can guide you.
Null · 2018-11-03 11:21
IT WORKED! all I did was reset the settings to default...which should have already been on default. :/
Mario Rossi · 2018-11-04 22:51
I am using the C++ stoi function to convert serial data to a string, but sometimes the connection is soykaf and I put some soykafty data in the stoi function, I just want this stuff to be ignored. Sure I can write something that checks if the string even consists of numbers, but the wierd thing is that when I tried a simple try catch "try {stoi(x)} catch (const std::exception& e) { cout << "error\n" }. The program still crashes once I put nonsense in the stoi() function.
Zuse · 2019-08-27 23:01
I don't have much to add, but this thread shouldn't die yet. What do you think about the future direction of C++?
Dozer · 2019-09-02 21:07
>>14911 >What do you think about the future direction of C++? I think it's heading in good directions, albeit a little slow. The Committee is aggressively pursuing a 3-year release cycle now, and C++20 will be a major release with contracts, modules, and ranges. If you're unclear why these are so important go study the papers & videos for a while.
roll · 2019-09-02 21:11
>>15009 >contracts I meant ''concepts'' *
Cheetah · 2019-09-08 17:45
I'm learning c++ and I have a lot of the basics down, but I've lost the inspiration and drive to keep going. Only thing that really peaks my interest would be learning graphics. What library would you recommend, and are there any good books to learn it?
SHODAN · 2019-10-21 19:40
>>15103 X11 AND GLUT DONT READ BOOKS
vector · 2019-11-16 03:01
>>15705 GLAD + GLFW is a much better choice with learnopengl.com
Nell · 2019-11-29 10:13
>>15132 You are correct anon. That and the Ranges library will propel C++20 forward in the functional programming arena. C++23 should actually close the gap on a few items and literally propel C++ right to the front of the pack in FP, given all the other performance benefits the language already has.
Unnamed · 2019-12-07 08:40
I am in the process of refactoring a text-based "game" (and by game, I do not mean anything that could resemble fun. It is merely a concept to help me learn C++.) My current problem is figuring out the best way to deal with updating a save file. There are only 8 variables being saved at the moment. (3 strings, 5 integers) -- Would it be better to use a template or an overload for this? I am under the impression that template is better for this scenario, as it is very simple. template <class My_Template> My_Template my_function ( My_Template argument ) { return argument; } should return any type needed. I have tested it and it works just fine. However, I am not sure if this is the correct way to handle this. What would you do differently?
Miho Iwakura · 2019-12-30 19:25
>>953 What.. exactly am I looking at here?
Jean Dupont · 2020-01-23 10:52
>>10767 MSYS2 + mingw is like cygwin but has the pacman package manager and is focused on native windows development without emulation. Not sure if you can use msys2 in a better terminal emulator than the one it comes with though
null · 2020-01-24 06:17
>>15103 SFML is good for 2D projects, although it also has an OpenGL interface so nothing is stopping you from going 3D if you really want to
Torvalds · 2020-02-11 04:07
>>6110 amazing piece of software, can you please consider adding some kind of manga-reading mode? usually my mangas are structured as the following Manga1/ Chapter1/ 001.jpg ... I'd like to be able to open Manga1, qimgv would sort the subfolders/images using natural sort and display them accordingly with the ability to remember the last position when viewing the folder so I can resume reading from where I previously stopped. thanks! keep it up
Unsigned · 2020-02-16 01:35
>>6110 Very cool. I'd like to get into C++ with a Qt project allowing me to quickly display images as a gallery and tag the files into a database. I was thinking about a feature to move all files with a given tag in a folder whose name is the same as the said tag. Or automatic renaming based on those same tags. I don't know if it make sense. Your "quick copy" feature is exactly the kind thing i'd like to make anyway I don't know if it's a reasonable goal, I know the very basics of C++ but not things like template, smart pointers or streams
Jane Doe · 2020-02-21 22:19
>>16927 >smart pointers smart pointers are simple, they just replace dumb pointers so you no longer have to remember to "delete" or "free()" them. /* demonstration of raw pointers * * pay attention to how SC and sds are created and destroyed */ #include <string> #include <vector> struct SomeDataStructure { float someFloat; std::vector<float> someFloatVector; }; class SomeClass { private: std::string name; unsigned dateOfBirth; SomeDataStructure* sds; public: SomeClass(std::string _name, unsigned _dob) : name(_name), dateOfBirth(_dob) {} ~SomeClass() { delete sds; } void initializeSomeDataStructure() { sds = new SomeDataStructure(); sds->someFloat = 93.50f; /* just fill vector with 1, 2, ..., 9, 10 */ for (int i = 0; i < 10; i++) sds->someFloatVector.emplace_back(i+1); } }; int main() { SomeClass* SC = new SomeClass("bob dole", 1923); SC->initializeSomeDataStructure(); delete SC; } /* demonstration of a smart pointer called unique pointer * * pay attention to how SC and sds are created * * notice how we no longer have to manually delete our pointers * as they automatically de-allocate when they go out of scope */ #include <string> #include <vector> #include <memory> struct SomeDataStructure { float someFloat; std::vector<float> someFloatVector; }; class SomeClass { private: std::string name; unsigned dateOfBirth; std::unique_ptr<SomeDataStructure> sds; public: SomeClass(std::string _name, unsigned _dob) : name(_name), dateOfBirth(_dob) {} void initializeSomeDataStructure() { sds = std::make_unique<SomeDataStructure>(); sds->someFloat = 93.50f; /* just fill vector with 1, 2, ..., 9, 10 */ for (int i = 0; i < 10; i++) sds->someFloatVector.emplace_back(i+1); } }; int main() { std::unique_ptr<SomeClass> SC = std::make_unique<SomeClass>("bob dole", 1923); SC->initializeSomeDataStructure(); } /* i never use raw pointers in C++14 because: * i'm lazy and don't want keep track of what needs to be deleted, * and more importantly, smart pointers significantly reduce accidental memory leaks */ >template /* hey we have two functions that do the exact same thing, * just different input type, wonder if there's a way to combine it into one */ #include <iostream> float calculateSomeFloat(float whatever) { whatever++; return whatever; } float calculateSomeInt(int whatever) { whatever++; return (float)whatever; } int main() { std::cout << calculateSomeFloat(22.4f) << "\n"; std::cout << calculateSomeInt(3); } /* now we have a "generic" function that accepts whatever * data type you give */ #include <iostream> template <class T> float calculateSomeGeneric(T whatever) { whatever++; return (float)whatever; } int main() { std::cout << calculateSomeGeneric(22.4f) << "\n"; std::cout << calculateSomeGeneric(3); }
Iverson · 2020-03-26 07:36
Hi lains, so during the lockdown, I have decided to start learning C++. Do you initialize your variables using C style (int x = 0;) or with parenthesis or brackets ? I like the C way for readability.
Netrunner · 2020-03-26 09:18
>>17559 >so during the lockdown, I have decided to start learning C++ I had the same idea. So far i've been using C-style for primary types and brackets for user-defined ones. I find it pretty readable.
FILLER · 2020-03-26 10:49
On the topic of learning c++. I have been going through A Tour of C++, and have a question for something I didn't quite understand from the way its described in the book, and i'm not finding any answers online. In chapter 6.2.2, he shows the following code cpp template<typename T, int N> struct Buffer { using value_type = T; constexpr int size() { return N; } T[N]; // ... }; after which he briefly glances over the purpose of the using value_type = T; Could anyone explain to me the purpose of having an alias like this, and how to use it in a program? Thanks.
Frank Garza · 2020-03-26 11:33
>>17559 Your question made me curious, and I found this: https://herbsutter.com/2013/05/09/gotw-1-solution/
Nameless · 2020-03-26 16:46
Need some quick advice here. I'd like to throw together a program with basic networking, gui (to the extent where it can display an image, a means of entering text). I only kind of know C++, I've written mainly commandline stuff but not in several years. Logically it seems like I should look into winsock.h usage, and either QT or wxwidgets. Is there a better way though? I imagine C# or python have better out of the box high level networking, but I don't know those languages.... I suppose the C++ knowledge could be useful later.
The Plague · 2020-03-26 17:37
>>17568 Well, if you're planning to use Qt, you can use it for networking as well.
Delilah · 2020-03-27 22:44
>>17568 >gui (to the extent where it can display an image, a means of entering text) tkinter, PIL >basic networking >out of the box high level networking depends what you mean by that. there's socket, urllib, requests, httplib2 et al. for python
Linda Lee · 2020-03-28 14:21
>>17008 Damn, the code formatting on Lainchan is really good. I'll take a good look at your answer tomorrow. I'm more into CTF and sysadmin stuffs now, but I didn't abandon the idea of learning C++ and will have more than enough time to tackle one those new concepts (as in, new for someone who always worked with garbage collected languages)
DEBUG-CONTENTS · 2020-03-28 22:40
I recently came across this and I wonder what the opinions are: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2137r0.html I saw it summarized, but I've read through it since it's short enough. This is a group advocating for C++ to ditch concerns about backwards compatibility, compiled interface compatibility, and drop focus and support for other platforms and constraints. I don't really have an opinion on it, because I don't use C++, so I'm curious what an actual C++ programmer thinks.
Crash Override · 2020-03-29 07:03
Is C++ a good programming language for someone that knows none to learn?
Splicer · 2020-03-29 07:50
>>17595 I think C is a better start because of its simplicity. There's less complex rules and abstractions, but you get the same benefits of low-level programming and memory management. You can also easily jump into C++ later.
Nobody important · 2020-03-29 09:18
>>17595 Python has a shallower learning curve than C or C++. You can put out simple programs quicker (simple GUI apps as well if you learn tkinter, or wxpython for more advanced GUI) from less time learning Python than any other widely-used language.
Liet Kynes · 2020-03-30 17:04
>>17595 C++ is a pretty horrible pick for a first programming language. It's an extremely complex and unwieldy language, even for people who've been programming for decades. If you're interested in the C family, start with Go. It's a lot like C, but much higher level, handling most of the lower level type things for you.
Miho Iwakura · 2020-03-30 19:11
>>17635 Feels strange reading this, 9 years ago everyone would say 'learn C or C++ you would get a solid grasp on programming fundamentals" now its just too complex? Let the guy learn c++ if he wants, he won't get an aneurysm out of writing tetries copies.
Wintermute · 2020-03-31 17:06
The only reason to learn C is to be able to find vulns in all the OSs right now. C++ therefore has no remaining use case other code golf. But even then C alone already has enough golf to last you years. So C or assembly are good to start with. C more so because you get to understand and exploit UNIX systems (so literally everything that exists right now) easier.
Wirth · 2020-04-01 00:14
>>17651 >C++ therefore has no remaining use case other code golf lol, that's somehow both cute and hilarious. C++ is entirely unsuitable for code golf, and has many important use cases (especially where performance is concerned). From now on, avoid topics you have no understanding of, no concept of, and absolutely no business commenting in.
Switch · 2020-04-01 01:22
Honestly, if you're going to learn C/C++ first, start with plain C. Get a handle on things like pointers and strings and the type system. THEN dig into C++. You'll have a solid foundation then, and it'll feel less intimidating >Learn go instead Don't. Go is an awful language. It lacks generics for instance (hilarious for a modern language) and is controlled by google (dangerous). >Learn rust instead Don't. The only appeal of rust is the novelty of a unique memory management strategy. In practice, the ownership/borrow system that allows their memory management to work is unwieldy, painful, and inflexible. The rather humorous thing is most practical rust code has "unsafe" sections strewn throughout it. It's basically a house of cards, and it will eventually collapse.
cond · 2020-04-01 19:25
>>17658 Go's very well designed, it just fits into a domain that I don't think most C++ programmers get. It's made with the idea that the code written in it is going to exchange hands thousands of times, with many contributions coming from the sort of codemonkies who write gigabyte large hello world programs. It lacks features as a means to prevent unskilled programmers from fuarrrking up, and to enforce a set way of doing things to make code easier to read. It's most definitely not a C++ replacement, but it's not trying to be one.
Cypher · 2020-04-01 19:44
>>17658 >and is controlled by google (dangerous). You shouldn't trust google, but I don't see how google can spy on you (or whatever it is that's dangerous) by programming in go. >>17636 It's not that you shouldn't learn c++, more that it might not be the best language to learn first. I think it also depends on how you learn it. For example, going through a book, going through some online documentation, a class, or learning it passively. I personally feel like c++ would be very odd to learn as a first language by myself, or at least how to write good c++ code. The language is giant and concepts such as ownership would be very confusing to me. A lot of good c++ practices and optimal code also requires a good understanding of "what's actually going on", and with c++ what's often happening in complicated. Not that it isn't good to learn those things, but for a first language it'd be difficult to learn those things (imo). Also from what I've gathered c++ has changed a lot over the past couple of years, which might explain the shift in attitude.
Knuth · 2020-04-12 06:23
Is std::string deprecated in favor of std::basic_string<type>? I mean, is it good practice to use std::basic_string<type> instead of std:string or std::wstring?
Zhora · 2020-04-12 09:10
>>17839 https://utf8everywhere.org
cdr · 2020-04-12 14:11
>>17846 UTF-8 is like kicking dead whales down the beach. Unicode does too. I dedicated an essay to rebutting that website.
Apoc · 2020-04-12 14:42
>>17852 not the point, it shows him that "good practice" of STL string type usage is platform-dependent
Nobody special · 2020-05-20 17:14
I'm just getting into C++ and I can't figure out how it handles memory. I know it has something resembling garbage collection, so what I want to know is how much of it I need to worry about myself and how much is taken care of for me.
BloodCat · 2020-05-20 21:12
>>18684 >how it handles memory The language just by itself (no user-defined class) doesn't really handle memory any more than C; i.e. local variables are put on the stack and are dropped when they are not used anymore, and calls to new (≈ malloc ) must be balanced by calls to delete (≈ free ). The difference comes when you define a class; creating an object of that class will call its constructor, and when you exit the scope (e.g. any block of code between curly braces) the object was created in, its destructor gets automatically called. So you can have an object whose constructor allocates memory and whose destructor frees it. Examples of such classes include containers like std::vector , std::list and std::unordered_map . Since the destructor is called automatically at the end of a scope, most of the time* you can say that all the memory managed by the object will be freed whenever it drops off that scope. tl; dr: it's like C if you don't use objects, and an object may free its memory when it goes out of scope. * Something to add is that the class can have something called a "move constructor" which allows you to transfer the content of an object to another. e.g. if you have std::vector<int> a = {1, 2, 3}; std::vector<int> b = std::move(a); , then b essentially stole the memory managed by a , and this memory will therefore be freed when b is destroyed rather than a . This can be useful to avoid copying all the memory, as would happen in that example if instead you just did std::vector<int> b = a; .
Turner · 2020-05-23 07:24
>>17687 Yeah, I'd argue programming languages are so easily modified by anyone that Google controlling Go is just not a concern. If users get too annoyed with the lack of features, they'll just write a transpiler/preprocessor/whatever that'll implement what they want. If suddenly Google adds weird soykaf to the compiler/tools, people will just write a frontend to LLVM or GCC (I think that already exists) and go on using that. Eventually, if concepts of the language really stick, Go-killers will spawn, as have spawned Julia trying to get the ML crowd out of Python, Zig offering an alternative to C (let's see how that pans out) or Nim taking influences from like 20 different languages. To make this C++-thread worthy, how do you start using modern C++ effectively? I'm asking because I learned the language as a "C with classes" type of thing, which sucked balls because I hate OOP and just hacking classes into C made me throw up. Now, as I want to learn it again "the right way", I'm at a loss. Every time I learn about a "new" feature, I read a couple comments in SO or some random blog saying that the feature has been deprecated, or it's just bad and I need to use x feature instead. Is there a book or whatever that teaches the language all over again starting at some recent iteration of the standard (C++17) to just forget all the "I still wanna be somewhat compatible to C" crust and learn C++ as a new language?
car · 2020-05-27 09:37
What is the best book to learn modern C++ for someone that already knows how to program?
Yu-ichi · 2020-05-27 11:54
>>18838 Try Stroustrop's tour of c++: https://isocpp.org/tour
BloodCat · 2020-06-14 09:58
I read A Tour of C++, I'm now thinking of reading Effective Modern C++ or a book on data structures and algorithms (such as >>145). Suggestions? I don't like reading more than one book at the same time.
Linda Lee · 2020-06-26 12:48
Alright Lain, I went through all the w3schools tutorials and exercises for c++ and I guess I get the jist of it. Where do I go from here, what projects should I start with to apply and learn? I'm thinking of making basic games and stuff. Anyone got any good resources or ideas to get started on some projects? Also, it would be cool if anyone knows of like a youtube series exploring game-making in c++ (or other pertinent tools)! Thanks ^^.
Lain Iwakura · 2020-06-26 14:01
>>19382 Now learn Vulkan.
Lunch · 2020-06-26 14:20
>>19382 If you're using C++, SFML is probably what you want. https://www.sfml-dev.org/tutorials/2.5/ All basic game code looks something like below. GameLibrary::initGameLibrary(); GameLibrary::Image doomGuy = new GameLibrary::Image("doom_guy.png"); int x = 0; int y = 0; while (true) { GameLibrary::draw(doomGuy, x, y); if (GameLibrary::keyDown("LEFT")) { x++; } else if (GameLibrary::keyDown("RIGHT")) { x--; } } Drawing 2D images and detecting input. The difficult part is the game logic. An excellent free book on implementing game logic is Game Design Patterns. I highly recommend the following chapters. They discuss the problems everyone runs into when they first start writing simple games. https://gameprogrammingpatterns.com/state.html https://gameprogrammingpatterns.com/game-loop.html https://gameprogrammingpatterns.com/update-method.html >>19383 I feel like SDL2 misses the point of using C++. If you're going to use SDL2, you're either going to base your code around a C library or write a compatibility layer. If you're not going to write a compatibility layer, why not just use C? If you're going to write a compatibility layer, why not just use a C++ library instead?
Yuki Nagato · 2020-06-26 14:30
If you're just starting out, try making a text adventure with an inventory system, rooms, etc. A proper text adventure is relatively easy to make, but it will still require you to learn the essentials like stateful data, memory management, I/O, types, and data structures.
Y.T · 2020-06-26 15:20
Thanks for the input! I just made a window in sdl2 and I'm gonna try to find some good tutorials to get started. I'll check out SFML too!!
Haruyoshi · 2020-06-28 09:47
How do i make pureC output LF instead of transforming it into CRLF when i compile for windows?
dictionary · 2020-07-09 00:55
i want to prepare for c++ exam most homeworks and exams involve writing something from stl that involves heavy use of templates so far we have written shared ptr, vector with strong exception guarantee, variant, thread pool, ratio and tuple i have failed all my exam attempts so far and want to prepare for the last one can you point me toward something in stl that i could be told to implement?
Nemissa · 2020-08-05 10:15
I was reading Ares's source code(an emulator) and I saw that pretty much every variable was defined with auto. I thought abusing auto everywhere was not ok, because it makes it harder to read a code.
Jet Black · 2020-08-05 11:45
>>19967 >I thought abusing auto everywhere was not ok, because it makes it harder to read a code. I read parts of the codebase, and the use of type inference didn't make it difficult to read. Why? Because for one, you don't need to know the concrete type; instead, it's more important to see and know what's being done to the data. Take a look a this piece of code: SomeItem item = produce(/* args */); read(data, item); process(item); write(item, file); Now look at this: auto item = produce(/* args */); read(data, item); process(item); write(item, file); The only difference between the two is that the latter code doesn't explicitly denote the type of item . You still have to know what you're doing to the data in both examples, and if you don't know what the called functions do, you're going to need to read the documentation regardless of whether you know the type of item The great thing about the combination of strong and static typing is the compiler is ensuring that your components fit together. By doing the compiler's work, you're gaining very little insight at the cost of more noise, needless redundancy, and fragility. But that's just me: What do you think? Do you find it difficult to read because of auto's prevalence?
Morpheus · 2020-08-08 07:14
I use vectors instead of arrays almost all the time because it's absurdly easier to implement functions taking vectors and returning vectors, is this a bad habit and I should actually figure out how to properly work with functions returning pointers to arrays or is it normal?
Terzibashjian · 2020-08-08 11:23
>>20102 >virtual functions Don't use 'em if you don't need 'em. And if you do need runtime polymorphism, C's alternatives aren't that much better. >that class object pattern Don't use it if you don't need it. >the black box memory management No such thing in C++. Destructors are deterministic, and even std::shared_ptr is just plain reference counting. >the unwillingness to use a simple array over your v*ctor soykaf Sometimes you do want extensible arrays. C would have you roll your own (probably badly), and either do so manually for every type, use soykafty macros or use type erasure (void* lol). >the lambda-in-critical-loops What a silly, random strawman. It's like if I cited "the function-pointer-calls-in-critical-loops" as an argument for why C is slow. >the using functors sillily instead of inline functions and scoped vars Kind of vague about what you find silly here. And using functors (actually lambdas with capture; who the fuarrrk still manually defines functors these days?) is just fine if it's not in a performance-critical part and/or the compiler is able to inline it. >the std algorithm god-awful technique Hey, guess what? std::sort is more performant that's C's qsort (^: That's what you get for being allergic to abstractions and not having proper generics (at least you've got _Generic lul). >the reliance on the cache fracturing of new() "the reliance on the cache fracturing of malloc()" fixed that for you. Also C++'s runtime polymorphism doesn't require you to use the heap; you can construct your object on the stack or in static memory, and then just take a pointer/reference of that. >10 tiered dependency injection with interface translation is better than just using globals One thing I'll agree with is that OOP "design patterns" can get really cancerous, really fast. Good thing that C++ is a multi-paradigm programming language and doesn't force anyone to use those, huh? >>20107 If you write C++20, you might want to use this for your array-like arguments: https://en.cppreference.com/w/cpp/container/span . Returning a vector is fine if you don't know in advance the number of elements in the result array; otherwise you could return an std::array (https://en.cppreference.com/w/cpp/container/array).
Lady Jessica · 2020-08-08 11:34
>>20107 Also, if you know in advance at runtime how many elements you'll push into your vector, you can use vector.reserve(n_elements) to pre-allocate memory and increase performance. Otherwise if you care particularly about memory usage you can use vector.shrink_to_fit() at the end before returning your vector.
Nell · 2020-08-08 13:06
>>20107 standard array would be best if you don't need dynamic structure of vector otherwise vector is okay only if you know your move semantics
pop · 2020-08-09 02:34
>>20129 >Assume I don't know the size at compile time [...] variable-length arrays are not a thing in c++ so i don't know how would you do it otherwise
Haruyoshi · 2020-08-09 05:19
>>20134 I see, thank you very much. >>20138 Alright, thanks.
John Titor · 2020-08-09 11:05
Uh, in view of the big controversy about C++ I just wanted to say, there are quite a few good books and articles that use C++ to get a point across. Most of the time I don't need to learn deep C++ wizardry to read them, but I do benefit from a sort of "nodding acquaintance" of the language. It isn't even that hard to understand. Then, paying employers pay money to write C++ code. So, I don't really see the issue. I don't use the language but I have no idea why people like to preach against a language. Isn't it more productive to use a language you like than to waste time complaining that /other/ languages exist? I seriously don't understand. Anyway, thanks for reading bye.
Mario Rossi · 2020-08-17 10:17
https://1337x.to/torrent/4596914/Oreilly-Learning-Path-Beginning-Cpp/
Ivan Petrov · 2020-08-29 04:53
i'm currently reading code where it's author initalizes every non-trivial variable like so: auto a{A{arg1, args2}}; Does somebody understand benefits of initializing a variable like this? As far as I understand, when done like so, a variable is implicitly copy-initialized, same as when someone does it like this: auto a = A{arg1, arg2}; So, there is no way to better initialize a variable than A a{arg1, arg2};
Tequila · 2020-08-29 11:57
>>20523 Check out https://gcc.godbolt.org/z/rWhbKz As far as I can see, all three forms are equivalent and just call the call the normal constructor.
Hiro Protagonist · 2020-10-09 23:48
>>20523 If a is supposed to be of type A then just do: A a(arg1, arg2); The only benefit in doing auto a{A{arg1, arg2}}; is when a is supposed to be an aggregate type whose value_type resolves to A. If using auto helps readability somehow (e.g. variable a is being initialized right next to some other local variable(s)), then auto a = A(arg1, arg2); could be used. As a general rule of thumb you should only use braces for default initialization or for removing the need to specify the type when pushing/inserting/returning a non-trivial type. In other words the author is retarded.
Meddler · 2020-10-10 08:55
>>20523 Some data structure libraries (like google's btree library) implement move semantics with the constructor but not with the assignment operator, which is why #1 is preferable to #2. Not sure why they would go with that instead of #3 though.
Haruyoshi · 2020-10-12 06:42
Been doing web Indian things for a long time now and wanna get back to c++ Any cool project ideas?
Faye Valentine · 2020-10-12 11:17
>>21254 All three of those just call the normal constructor, though. Even auto b = std::move(a); will call the move constructor rather than the assignment operator. To invoke the move assignment operator, you need to do it after the new variable is defined; e.g. A a; A b; b = std::move(a); or A a; A b; std::swap(a, b); . >>21333 Implement a virtual machine. Implement a simple scripting language. Create your own game engine from scratch using OpenGL.
Backus · 2021-01-08 18:08
>>23808 >an exocortex What is that supposed to do exactly? >someone wanna comment on improvements? Sure. I would recommend not #including .cc files and only #including your .hh files, because otherwise at some point in the future the linker may complain about multiple definitions. Remember that #include essentially just copy-pastes the content of a file into another, so the same definition may end up copied in multiple files. Also, all string& arguments could be made const string& to emphasize that the function doesn't modify the original string. For functions that consume strings like exo::Entity::Problem::Problem you could also pass the string by value and use std::move at the call site and inside the function to avoid unnecessary copies. Also you might want to have a makefile of some sort.
Yu-ichi · 2021-01-12 09:15
>>23819 >not #including .cc files >makefile ah i've decided to give *.cc files to the compiler and include headers where needed >could be made const string& to emphasize that the function doesn't modify the original nice, never would have thought of this >What is that supposed to do exactly? it's a hierarchical note-taking app made a lot of money using a higher-level prototype so now i'm aiming ot create an actual program i've made some changes if someone'd like to code review https://github.com/apocpublic/exocortex/pull/4/files this PR will be open for a long time as i'll try out a vertical git branching strategy with this project
XERXES · 2021-01-25 16:41
Did Stroustroup actually intend for people to directly throw and catch integer error codes in programs or did he just make anything throwable and catchable because he thought adding an exception class was inappropriate?
Leto Atreides I · 2021-01-26 08:18
>>24122 That's not really directly built into the language tho, it's in the STL.
Erik Johansson · 2021-01-26 14:41
>>20130 I haven't found any. I recommend reading Stroustrup's Programming: Principles and Practice Using C++ if you are complete beginner or Lippman's C++ Primer if you already know how to program.
protected · 2021-01-26 20:23
>>24136 I don't really see the point of baking any specific class into the language, though. If a library solution is good enough, why further complicate the language? And maybe for some people std::exception is not exactly what is needed, so they would make their own exception class or throw error codes, or what have you.
Ishikura "Tatsu" Tatsuhiko · 2021-01-28 08:26
What's means it exactly? int main(int argc, char **argv)
DEBUG-CONTENTS · 2021-01-28 14:38
>>24178 argc is the number of command line arguments - 1. argv is a string array of all arguments passed, starting from 1 (argv[0] would just be the executable name). #include <iostream> int main(int argc, char** argv) { if (argc == 2) std::cout << argv[1] << std::end; return 0; } $ g++ test.cc -o test.exe $ test.exe hello hello Since pointers are the same as arrays, you might also see argv as char* argv[] . Both are perfectly valid.
kristakqo · 2021-04-15 01:14
Is SFML worth it? I know the basics of c++ and some SFML and I don't know where should I go from there.
Lady Jessica · 2021-04-15 04:26
>>24189 >argv is a string array of all arguments passed, starting from 1 (argv[0] would just be the executable name). It's possible to increment the argv pointer (argv++) to get your command line arguments 0-indexed.
alexandra · 2021-04-15 22:12
>>25448 probably, but just don't
Yuki Nagato · 2021-04-21 05:52
What version of the standard do you write your C++ programs in ? I see the majority of the reference books targeting c++11 or c++14 but what about c++17 and 20 ? Are compilers up to date with the changes ?
Tank · 2021-04-21 18:27
>>25560 you should be using c++14 at minimum due to std::make_unique which replaces new. c++17 has std::optional which reduces boilerplate you would otherwise write for contains-no-value-but-not-an-error cases. c++20 compiler support and adoption is a work in progress.
Morpheus · 2021-04-24 12:26
>>23894 >>23808 >>23819 tons of experiments later i realized this is just a stack manager, you push things on top and pop them off it's minimal and it werks https://git.sr.ht/~ap-oc/stax
Nanashi No Gombe · 2021-04-29 12:41
how do I find projects to contribute to? I was thinking of contributing to SerenityOS but it's a monster of a project now.
Mitnick · 2021-04-29 12:42
>>25639 honestly just scroll through github
Jane Doe · 2021-04-29 18:34
What is it that you like about C++? Whenever I see C++ it induces nausea in me, so to those that enjoy C++ I would like to hear your perspectives.
list · 2021-05-01 10:57
>>25649 compared to C: not having to worry anymore about forgetting to free memory by using smart pointers only, not having to reinvent the wheel to create common data structures, not having to worry about security/memory issues involving string input and manipulation. all of this for very little to no overhead (except for the latter two in a very cramped embedded environment where a 100KB larger executable is the end of the world).
pop · 2021-05-02 11:49
>>25649 I've never touched C++ in my life but I unironically like the syntax
null · 2021-05-02 13:58
>>25649 The utility of C++ is well illustrated by a simple template like std::swap. I wanted to make a swap function for a struct in C and it was needlessly obnoxious. Maybe could have done it with a macro, whatever.
Hiro Protagonist · 2021-06-11 00:48
>>25639 Serenity OS is one of these projects that makes me want to learn modern C++ So lainons, I have to choose between Rust and C++ and I get the feeling that C++20 is the right choice because, first of all I like C syntax, second of all, C++20 is a lot like Rust, but with all the traction of 40 years of adoption. So why bother with Rust ? Subsequent question : what are the best ressources to learn c++20 ?
synchronized · 2021-06-11 16:13
>>26195 not really qualified to answer your question, but > C++20 is a lot like Rust it's really not.
Koos van der Merwe · 2021-06-11 18:39
>>26211 They're both over engineered, have ugly syntax, and require manual memory allocation. A C++ programmer dropping lambdas and iterators should be working at the same level as a Rust programmer.
over · 2021-06-20 06:16
>>26312 When I say this, I don't mean to use the cfront compiler from 1985; but rather just learn C, with classes. After that, you should dabble in C++11/14/17/20 features and the STL.
Frank Garza · 2021-06-21 13:26
>>26321 There is no plain C with classes. Do you mean for that lainon to implement a class system? Or for them to use glib's stuff?
Eldon Tyrell · 2021-06-21 15:05
>>26327 He probably means for anon to use C only(avoiding the Standard Library) + classes at first. A really bad idea, anyway.
if · 2021-06-22 03:45
>>26329 What is the right way to learn it, then ? What's your take ?
Koos van der Merwe · 2021-06-22 06:01
>>26330 https://isocpp.org/wiki/faq/how-to-learn-cpp#start-learning Can't do better than this.
r4444 · 2021-06-22 08:18
>>26329 Notice how I said C++11 through 20, I didn't mean as in no C++ features. I meant to learn C++98, then go beyond. This is what most tutorials seem to do at least.
Neo · 2021-06-22 10:25
>>26333 >I meant to learn C++98, then go beyond. This is what most tutorials seem to do at least. I think that's a terrible practice. Tutorials should always show the correct way to declare pointers (std::unique_ptr) and allocate memory in heap (std::make_unique), NOT "new" etc. I don't care if the C++ tutorial is showing the basics of OOP, it's these kinds of tutorials that produce memory-leak-causing novice C++ programmers, whose memory bugs are then used as "evidence" by Rust evangelists who produce sensationalist "studies" that imply that their language is so perfect and C++ is so dangerous that everyone needs to abandon it.
swap · 2021-06-22 12:29
>>26336 Bjarne's own book for beginners uses new when he is explaining pointers at first. The first time you see std::unique_ptr is on chapter 19. And that is when he is teaching how to make a "vector" class like the one in the standard library.
Morpheus · 2021-06-24 01:19
>>26331 Got my tour of c++, 2nd edition. Damn Amazon is fast.
John Rain · 2021-06-24 22:50
>>26340 Huh, You should never meet your heroes, i guess.
Judge Fang · 2021-07-05 17:45
>>26376 it makes sense when you think about it. Most of his books are written to be used in a classroom, and any freshman/sophomore CS course WILL force you to use raw pointers. I'm reading A Tour of C++ which is intended for a different audience, and he mentions unique_ptr quite early
Hiro Protagonist · 2021-08-12 09:04
I'm a newb. Someone give me a perspective, please, on the role of memory allocation in this language? I ask because I heard that in Modern C++ manual memory allocation can and should be avoided almost always. So what are the memory allocation capabilities of the language used for and in what circumstances, generally?
typedef · 2021-09-22 20:50
Been interested in learning C++ as my first language but it seems scary, also I don't know if there's a book or tutorial that explains build systems, conan, premake etc. However I've heard that Meson and Ninja let even fools compile soykaf because they automatically create makefiles you can use, but even then I'm not sure if that's true or just half-truths I've squeezed out from the C programmer mindsponge.
DEBUG-CONTENTS · 2021-09-23 06:54
>>27591 >first language >build systems I would just use an IDE with a little "play" button that does all that for you. Trying to learn how the build system works at the same time as learning to write code will just be a waste of brain power.
over · 2021-09-23 17:36
>>27591 code blocks is a free ide that lets you build projects without messing around with "build systems". build systems are a waste of time, just have a batch script (windows) or bash script (linux) that calls the compiler. (or use code blocks) you only need to run the compiler once (1 compilation unit), splitting it up confuses things. learning how the preprocessor works is much more advantageous than a build system, preprocessor is inbuilt to c so you can't get away from it, build systems are additional jank on top to unnecessarily make things more confusing.
Hopper · 2021-09-25 11:09
>>27652 Lol. They're not entierly wrong. Go's very much a babby language, designed to keep code monkeys from breaking things. The majority of Go progrmmers are retards, so it gets a lot of flak from people who actually know what they're doing. I still recommend it to beginners though. It's a very simple language that's hard to get lost in. And unlike, say, PHP or Javascript, it's close enough to a 'real' language that it won't turn you stupid.
Anamika · 2021-09-25 15:40
>>27663 Ok! Thanks for the advice anon!
null · 2021-10-11 19:39
>>27914 I fuarrrking hate my day job. Every day is the same. I connect to my zoom call of the day and hear the first of five scrums to be had that day. Then I take a look at my tickets for the day and groan. It's another add 500 features using a soykafty, buggy API without any documentation using C styled C++ because the higher ups don't want to update to C++17. I don't really remember what I even do at work anymore it's that dull. I just know that work what I preoccupy myself with the most and also the thing I hate the most. I've really considered killing myself often but there are no other jobs that pay as well as C++ jobs, and you can't go to heaven if you kill yourself either.
William Holtzer · 2021-10-13 00:02
>>27925 >No insane overcomplicated template metaprogramming That's the only way to write C++.
John Rain · 2021-10-26 22:08
>>27925 so you're in HFT? how do I get into that field? I'm graduating soon from a no-name university
Boole · 2021-10-26 22:11
>>27922 >there are no other jobs that pay as well as C++ jobs this isn't true. In fact, some C++ domains (embedded, gamedev) tend to pay lower than average. There are juniors writing soykafty Java CRUD apps for a living earning 200k+. Some places would pay you half a million a year if you're willing to put up with COBOL
Knuth · 2021-10-27 00:08
>>28262 >There are juniors writing soykafty Java CRUD apps for a living earning 200k+. Do they also live in areas where rent costs 2/3 of that in a year?
Ender · 2021-10-27 07:04
>>28262 >Some places would pay you half a million a year if you're willing to put up with COBOL source? >>28263 there are studio apartments in san jose for $1400/mo
Church · 2021-10-27 19:41
>>28261 Not that lainon, but I was in HFT for a while and know people who still are. If you're a skilled programmer and have strong algorithms knowledge just apply; they're desperate for talented people since any grad who can get into a quant shop can also get into FAANG. The interview process is pretty nasty; you're expected to write a decent amount of fairly elaborate code rather than the leetcode style questions you get elsewhere and maybe bullshit personality assessments and IQ tests depending on the firm. Just know the ridiculous pay comes at a price. 10+ hour days are standard and you won't meet a single person there for whom work isn't the absolute, overriding concern in life. 5-6 years is a long tenure at these places; they call Google a retirement villiage for a reason. Maybe consider an internship first if you still have enough time in your degree.
Joe Bloggs · 2021-10-27 20:29
>>28285 holy soykaf. I want my job to be challenging, but 10+ hours? they can fuarrrk off with all their money. Are there any fun software domains left that are fun and not exploitative? I figured HFT was one of the good ones, that's one of the reasons why I've been learning C++. I just wanna do actual programming beyond wiring up CRUD apps, without being overworked. I don't even care about high pay, honestly. even 60k is enough for me.
Faye Valentine · 2021-10-28 18:55
>>28288 You WILL work for 10 hours a day for 5 years. And you will be happy.
Undisclosed · 2021-10-28 20:18
>>28288 I wouldn't go as far as to say it's exploitative, at least where I was SWEs were treated very well. You get all the perks of being at a cashed up tech company - free breakfast, lunch and dinner plus any equipment you could desire - with a lot more independence and relatively little bureaucracy. The work itself is extremely interesting and flexible too as long as you're getting stuff done. I wrote a relatively large system in Erlang simply because a coworker and I had been looking for an excuse to get into the language and a few of the guys more connected with trading use APL heavily too. The thing I appreciated least while I was there was the absolute feeling of liberty that comes from all software being internal and having your clients within shouting distance at all times. My working life now feels like it's 90% dealing with boring user experience and backwards compatibility crap. If you can take the ruthless nature of finance (you WILL sign an NDA when you join and a no-compete when you leave) and don't have any external ties like a family it's quite the gig.
Anamika · 2021-10-30 06:55
I am looking for a problem set and well explained solutions to these problems ordered according to a learning path / skill tree. May it be a guidebook available only on Library Genesis, may it be a code kata git repository, whatever. I have tried https://exercism.org/tracks/cpp/ exercises, but they do not seem to be structured didactically. There is no path or skill tree, just a set of problems tagged according to loosely defined "difficulty". Thank you.
Morpheus · 2021-10-30 17:46
>>28319 There are two books on a polish programming competition that has some problems and for each problem, the winner of it explains how he solved it. Libgen has those two books(in english), I don't remember the titles(many just polish programming) but given that they are from competitions, the skill level is not low.
Aristóteles Amadópulus · 2021-10-31 04:58
>>28331 I imagine they lacking in the basics… and I cannot read Polish. What I have in mind would ideally start with an `std::cout << "Hello, World!";` "change the stuff printed" problem, through variables and built-in types, loops, functions, classes, pointers, rule of zero/three/five, standard library, and then library writing, maybe even adding some CMake for good measure. Each one with a well documented solution that points out the pitfalls of each problem. I have tried looking at Principles by Bjarne. It has a few exercises, but I do not see well documented solutions. It might or might not be a gargantuan effort, but Bjarne, for example, already writes Cyclopian tomes able to save your life if hit with a direct hit of a mortar shell, so I do not see any real problem here…
Gyula Kovacs · 2021-10-31 10:28
>>14445 Use C++11 or the latest. >>17595 >Is C++ a good programming language for someone that knows none to learn? In my opinion no. Read the 2nd edition of Bjarne Stroustrup's Programming: Principles and Practice Using C++. I recommend starting with How to Design Programs, 2nd edition: https://htdp.org
Hiro Protagonist · 2022-03-16 12:18
Any book c++ recommendations for someone who can program (java and c#) ?
Tequila · 2022-03-16 14:29
C++ books * If you don't know how to program, read Programming: Principles and Practice Using C++, 2nd edition by Bjarne Stroustrup. (aka PPP2). * If you know how to program but don't know c++, read C++ Primer, 5th Edition by Stanley B. Lippman; Josée Lajoie; Barbara E. Moo. General tips and links * Install GCC or Clang. Also, install cppcheck, gdb, valgrind and afl. You also need an editor, like Emacs, Neovim or VSCodium. (VSCode is a botnet) * Do use things like -fsanitize=address https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html * Follow a style guide: https://suckless.org/coding_style/ * Use a reference: https://en.cppreference.com/w/ * https://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html * https://lwn.net/Articles/250967/ * https://blog.regehr.org/archives/213 * https://dl.acm.org/doi/10.1145/103162.103163 or https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html * Use include guards: http://www.cs.kent.edu/~nmadi/CS2/Notes/include_guard.html and http://faculty.cs.niu.edu/~mcmahon/CS241/c241man/node90.html * If you are looking for a GUI lib, use SDL. FLTK, wxWidgets or QT. (tk is also an option) SDL tutorial: https://lazyfoo.net/tutorials/SDL/ * Use version control: Git (recommended): https://git-scm.com/book/en/v2 and https://www.atlassian.com/git/tutorials Fossil: https://www.fossil-scm.org/home/doc/trunk/www/quickstart.wiki * https://godbolt.org (compiler explorer) * Use makefile: https://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/ or https://makefiletutorial.com * Use the recommended compiler options: -std=c++17 -Wall -Wextra -Wformat=2 -Wformat-truncation (perhaps also add -pedantic Also, clang also has -Weverything) * If you build a debug build, add -Og -g -g3 options. * For security, use -D_FORTIFY_SOURCE=2 and -Wl,-z,now and -fstack-protector-all and -fstack-clash-protection compiler/linker options. (don't use -fstack-check) * Sometimes changing compiler optimization options/the compiler/using musl instead of glibc (or other way around) can unearth bugs in your code * Read Programming Pearls, 2nd edition by Jon Bentley >>30428 C++ primer by Lippman et al.
if · 2022-03-19 15:17
Which C++ build system to use? It seems that good old makefiles, mk and bmake are the suckless choices, clearly. But what about Cmake and Meson+Ninja? To me, it seems that Meson+Ninja is the better choice. Also, Boost.Build https://www.boost.org/build/ is a thing wtf? >>30430 >* Sometimes changing compiler optimization options/the compiler/using musl instead of glibc (or other way around) can unearth bugs in your code > Musl instead of GlibC I think you meant libc++ instead of libstdc++, since this is C++ thread. But otherwise a good point.
Yuki Nagato · 2022-04-14 03:22
>>30430 Excellent recommendations Lainon, thanks! >>30453 >Which C++ build system to use? I use Mesonbuild, and I'm pretty happy with it to be honest. https://mesonbuild.com/Reference-manual.html
Pris · 2022-04-14 04:10
>>27104 >I heard that in Modern C++ manual memory allocation can and should be avoided almost always. Correct. While you ''can'' go right down to the hardware if you'd like, using the STL is almost always a much better choice. The 'hardware' point is easily demonstrated thus: ''The STL itself is written entirely in plain C++''. This pretty much shows it's ready for real-world, industrial-scale use (since the STL is really big & layered). One of the most important -- possibly ''the'' most important reason not to use manual memory control is exceptional states. It's difficult for a human being to even ''imagine'', much less properly manage, exception states in a big system. By using RAII + exceptions (which the STL does extensively) managing this issue becomes a snap actually. Another reason is that if you are dealing with a typical, real-world, convoluted set of data structures, trying to optimize all that by hand can be nigh-on impossible to do well. Again, using the STL instead with it's strong reliance on Template Meta-programming can often result in ''faster'' compiled code by modern optimizing compilers, than any reasonably dev-time-constrained code by hand. The compilers can munge all these data together in memory-layout amalgams than can be frankly hard to believe. >tl;dr There are several other reasons, but speed + error management are the easiest to appreciate.
cond · 2022-09-28 23:06
>>16927 I would advise to stay away from Qt if you are targeting Windows, Its quite a pain in the ass to compile your app with static Qt while retaining c++20 functionality.
Donna Hawthorne · 2022-11-18 23:15
>>19971 >Do you find it difficult to read because of auto's prevalence? Not that Lainon, but no. As you well-stated, it's not essential that I know what a concrete type is generally, b/c I use intentional naming. I'm much more interested in the system than the parts. And ofc, if I ever need to actually drill-down into a user type (as during maintenance), the modern world has modern IDEs. It's instantaneous to get to either a declaration or definition when needed, and the 'surface' of the codebase remains clean and readable otherwise. That brings up another valuable characteristic of C++ auto, namely ease-of-maintenance. If you've specified all your user functions using the "auto w/ trailing type specifier", then as long as you make sensible changes you can completely rework the internals of a function and none of the dependent callers need care what the concrete type is assuming they are also using auto at the call-site. In either case, auto is a big win, and a huge boon for C++ devs. I understand completely however why C guys hate it, but w/e. I only use C when I must these days, and that's more & more rarely.
Wirth · 2022-12-02 14:27
Why including libraries in C++ is still horrible?
Yamaoto Toshi · 2022-12-04 12:02
>>33572 It's one of those things C++ inherited from C and can't change because it's so deeply ingrained in the language and its ecosystem. Other language features have helped to smooth things over, but fundamentally, it's the same "dump the contents of file a into file b" system from the 1960s.
Anamika · 2022-12-04 12:05
>>33609 Actually, it was from the 1970s. These problems were solved in the 1960s.
Random · 2022-12-05 05:34
>>33620 Thanks for the answer. It's a bit much, looks like it's time for me to go through some basics but at least there is couple of useful sounding keywords there.
dup · 2024-11-23 17:30
bumping an actual lainchan thread from being killed by 4/g/ shallow feelings discussion threads.
Anonymous · 2024-11-26 16:17
>>33621 I wish to know what the poster said originally. Seems that the post is gone now...
Leto Atreides I · 2024-12-01 21:17
What I really love about C++, is that is like those screwdriver sets that have a lot of different tips. Perhaps ironically, I have encountered at least similar comments regarding these kind of tool sets: >> "There are too many tips!", "Why so many tips?", "What is this tip good for?" Regarding C++, the most common complaint is: >> "It's too bloated!" You know, I like to see C++ this way: The 'tip' is there available to use it when you need it, but you don't have to; you may omit its use. You can reserve those 'tips' for specific occasions, or you can never use them at all. They may come in handy at some point (as, in fact, has happened to me). I hope I make myself clear (my writing is like kicking dead whales down the beach), ha, ha. However, I may be wrong; I am being honest when I say that I am not an expert in Computer Science. I completely understand people who prefer a more “a tool that does one thing, but does it well” kind of perspective. I am not bothered by points of view opposite to mine. I should add, that I prefer it over C because of the Object Oriented approach.
Molly Millions · 2024-12-02 08:06
>>40540 I've always preferred C because I prefer simple, but I'll never deny the utility of a Do Everything language like C++. It's really nice to be able to soykaf out a complex program in three seconds by gluing together parts of the STL.
Wander · 2024-12-07 07:20
I'm a Rust programmer and I've been learning to program in C/C++ for a while now and every time I try to do something a bit complex I spend most of my time debugging because the compiler doesn't give me any useful data and debugging with GDB is quite a chore. How do more experienced programmers deal with this? I've seen some people use Visual Studio for debugging but it's not available for Linux of course.
Gyula Kovacs · 2024-12-07 08:49
>>40614 output to console or log file? >I spend most of my time debugging because the compiler doesn't give me any useful data and debugging with GDB is quite a chore. collect and output the "useful data" you're looking for with printf? write your own error messages / asserts. if various debug messages should never be shown to the user then turn them off by surrounding them with #ifdef DEBUG_BUILD and #endif macros. i never use a debugger, not realistic for my case. you can also write unit tests for every minute detail but if you have strict deadlines and your project isn't supposed to be some clean pristine open source project that can be delayed constantly you don't have time for that soykaf.
Drano · 2024-12-14 16:34
>>40614 >I spend most of my time debugging because the compiler skill issue bad code == bugs, it's really that simple. You may be programming C++ as a Rust programmer instead of programming C++ as a C++ programmer. Think in C++ syntax instead. >Visual Studio for debugging but it's not available for Linux of course. Visual Studio Code is available for Linux, so you may mean VS Community Edition.
Ivan Horvat · 2024-12-16 21:17
>>321 >>301 >>343 Necroposting, I know, pls no boooly. 7 years later, these solutions are still dogshit and worth ranting over. Recommending boost, std-anything, and joke proposals always cames across and will always come across as some sort of sadist prank. The problem is 99% of "C++ developers" don't actually develop a single god damn thing. Both in terms of implementations and in products. Instead, they spend all day circle jerking their zero cost abstractions and limited wrappers that, at best don't work well in real world products, or at worst aren't tested and wont/fundamentally cannot work as expected. Take ASIO for example: It's trashware that requires you to manage IO buffers all by yourself, you'll probably end up introducing some bullshit leak, introducing some heap violation by not pinning the owner of some resource by lambda capture (yes, out of all ownership paradigms they chose lambda captures to keep resources alive, making Qts model of ~T(){getParent()->remove(this)} look reasonable), just to end up losing your packets because of teletype optimizations. Yes, you heard that right, I'm blaming teletype machines for the reason why a noob would get packet loss under ASIO. You need to go out of your way to figure out that nageling is a thing, how to disable it, just to submit data you've already buffered. Somehow this objectively bad abstraction makes ASIO "low-level" according to orange site and redditors. It's insane. Give me a damn buffer to read from once you've buffered enough bytes pursuant to a user provided callback, give me a send buffer that gets flushed per tick, and then if you want to be low-level, give me the fd. It shouldn't be this messed up. Another example, related to the reply chain, the god damn filesystem library: The filestream wrappers under most modern STLs and CRTs are layered upon so much trash that targeting 32bit builds almost guarantees you're going to break offsets above 31bits. And that's skipping over the aforementioned CRT bloat that's going to handle stream caching on top of whatever the OS is doing. The bloat and code smell is such a liability it's unreal. But, hey, as least we have committee and academic midwits arguing over path builders and += operator overloads, am i right? Better yet, how about just let me readv/writev in peace? I could go on and on over other Boost and STL additions. Boost process is worthless. ASIO is worthless as an event loop. Locale translation is next to nonexistence - they'd rather soykaf up the spec with more string templates than define a few relevant codepages and BOMs modern systems should be able to handle. But, hey, cant wait for astroturfed reflection they're totally not going to screw up in current year + n.
Marly Krushkhova · 2024-12-17 14:21
>>40719 Expect it to get worse because there recent news is that a c++ lead dev got booted over triggering some CoC riders with a benign question. Should be indicative where the ship is going. As for fast file access you can use C functions. Had to optimize file IO ~4y ago and it was stupid fast compared to standard c++ approach. I think in general you cant trust any long standing committee because they will run out of real work and start creating bullshit just to stay busy.
Batou · 2025-01-16 05:34
>>38 I have written many tools in my time, some java, some C, some python. Mostly C++ though, and mostly terminal or server stuff. I have also tried many GUI toolkits/libraries: Android Studio, GTK4, Tkinter, WxWidgets, the Visual Studion C# soykaf. Even the "oh so programmer friendly" Dear ImGui. They're all a pain to use. I fuarrrking hate it, they all leak abstractions, the code is ULTRA verbose, it takes ages to debug, and GTK in particular expects you to use their data types, logging, and basically adopt their dialect if you want to properly use it. Documentation is never all in one place, and searching for stuff gets you results from older versions, full of depricated features. I end up abandoning my GUI projects in the long term, because of all the hassle and complexity it adds. What the fuarrrk lainons? Is the GUI actually the most time-consuming and error-prone part of programming? I'm spending more time on wrangling GTK than on the actual feature code. Is there a better way than this?
Otto Normalverbraucher · 2025-01-16 09:15
>>40968 >What the fuarrrk lainons? Is the GUI actually the most time-consuming and error-prone part of programming? I'm spending more time on wrangling GTK than on the actual feature code. Is there a better way than this? Now you know why everything is an Electron app. Since it's a C++ thread you might find Qt nicer to work with than GTK which was designed for plain C/Vala. Also there are GUIs for building GUIs like Qt Designer and whatever gnome calls their thing, that might be worth a try.
Tyrell Wellick · 2025-01-16 14:30
>>40968 >>40970 Yes anon I should specify, I meant advice/library recommendations for C++ specifically. Kinda wrote that post in an emotional state of frustration
Case · 2025-01-18 01:40
>>40971 Not exactly the answer you're looking for, but what you described is why I empathize with you and try to use CLI over GUIs.
Debbie Charteris · 2025-01-18 02:26
>>40968 Yeah, writing GUI is like kicking dead whales down the beach. Whenever I need to, I just run a webserver. It would be cool if there was a decent standard to display images in a terminal so that I wouldn't need to.
Agent Smith · 2025-01-18 08:06
I find it odd how everyone writes declarations like int *foo; float bar[16]; as opposed to int * foo; int bar [16]; I find the latter a lot more readable at a glance, and a lot clearer about what it actually is.
nil · 2025-01-18 10:14
>>40978 I personally prefer int* foo; because it makes more sense since foo's type is "pointer to an int". The problem is that it gets confusing when declaring multiple variables at once. int* foo, bar; declares one pointer and one integer.
Demeere · 2025-01-18 10:26
>>40978 i write like that because
Yuki Nagato · 2025-01-23 01:22
>>40968 I'm learning GUI programming through QT and it's great! The documentation is excellent and everything makes sense. I do not have experience with any other toolkits thoughalbeit
Cat Mother · 2025-01-23 07:26
>>41007 I think QT works well for hacking a gui fast together but i got frustrated when trying to make it look good & implementing custom elements. I.E. you can style with CSS but then one element has some inlaid element that overpaints your global background definition and you have to find whats its name to fix it. TLDR was nice for hobby project minimum functional gui but another nightmare for a professional looking gui with custom design.
Emmanuel · 2025-01-23 13:49
>>41009 btw this wasn't to demotivate you. If someone disagrees with my qt experience im happy to get corrected on how to do it right.
push · 2025-01-24 13:23
Until recently I was programming in C and when I did so, I formatted most of my files in this order: - Headers - Defines - Constants - typedefs, structs and variables - function prototypes - Main - the actual functions sorted chronologically However, with learning and using C++ this introduces templates and classes. Where do you put those? In a way their are similar to structs and variables, so I might want to put them there, although they of course also have functions, so this would imply putting them down? I'm very confused on how to do this and on what is a good programming style in C++. Currently my C++ programming style is just the same as in C with some additional C++ quirks, but I want to dive deeper into C++ and this requires better formatting/style.
SHODAN · 2025-01-24 16:35
>>41022 a template is just a placeholder datatype that's filled during compilation, compiler generates a copy with each data type you used. You dont place it anywhere specific, you use it for classes/functions you dont want to rewrite for multiple data types. For classes you want generally 2 separate files. Define the class in a lightweight header file and implement it in another .ccp file. The point is to speed up compilation as include will only have to read the tiny header which stacks up if you have many include points. Also C++ structs are just classes with public access as the default (class is set private by default) So its not just a data package like you would expect from C and can include functions as well as constructor/destructor
5C4R3D_L053R · 2025-01-25 11:15
Is it possible to get a job using C++ as a beginner? A little background about myself... I have had a couple of programming “jobs”; the first was a migration project using PHP and the other one was to develop a back-end application with Python. However, they were informal (freelance) and I have no way to prove the experience gained (it was a long time ago and I was more of a novice than I am today and did not use Git). I can program with C++ without problems, but I have never used it in a professional environment. I know the basics: How to compile and link libraries, how to use the preprocessor, when and when NOT to use pointers, among other details about the language. I have only written “toy” programs, but never developed anything really useful. By the way... I have no degree; everything I know was acquired through self-learning. I am not interested in the pay, what I want is to get a job and gain experience and learn a lot. In which projects is C++ most commonly used these days? Do I need to know a lot about low-level programming? I really like the language, but I am afraid of not getting a job with which I can support myself financially. Also, I do have considered contributing to open source projects, but I am scared of not being suitable for the job. Thank you very much in advance.
Dr. X · 2025-01-25 12:56
If I want to implement some of vector's functionalities myself, is it possible to resize an array on the heap without copying its values into a new array? Let's say the original array has 10 elements and I want to increase its size to 12 (or even decrease to 8 and delete the last 2 values!), can I pop/push to the end of the array's memory block? I just read about how that's not possible but I wanted to double check. And in a 2nd scenario if the array was on the stack would I be able to decrease/increase the memory block in that fashion? Or is the only way I have of dealing with it the pointer pointing to its first element representing the block as a whole?
The Plague · 2025-01-25 13:29
>>41027 It is possible to resize arrays on the heap, kind of. In C, realloc will only copy the array to a new memory location if it cannot allocate room in the next block. I think the only C++ replacement for realloc is std::vector. Another possibility, if you don't mind losing the O(1) access times, is to use a linked-list (O(n)) or a binary tree (O(log(n)), if well balanced). That way, you can enlarge your list by allocating memory for a new element and shuffling some pointers, without moving all the data. I'm not aware of any way of directly manipulating the stack pointer in C/C++, so I don't think you can do it that way either.
John Titor · 2025-01-27 16:27
>>41028 Something else just occurred to me, even if it isn't proper resizing: let's say I have a 10 element array and want to resize it to 7, if I just set the last 3 positions to null would that make any difference performance wise? That slot would still be reserved for a value but now there is no value in there, even if it can't be reallocated to something else.
Tank · 2025-01-28 00:51
>>41049 That's definitely what you should do. There is no reason to free memory that might still be used.
Iverson · 2025-01-30 13:09
>>41027 Using the standard library: Not without allocating more memory than initially required (e.g. when creating an array of 8 elements, actually create an array of 64 elements under the hood. Now resizing the array up to 64 elements is doesn't require any copies). If you go straight to the operating system: Yes! (assuming we are talking about processors with virtual memory). The operating system (usually) allocates memory using 4KiB pages. You can tell the OS to "reserve" an address range without requesting any actual memory. So you can e.g. "reserve" 1 GiB of address space, but only actually allocate the first 4 KiB page of memory. And when you resize your array, you need to allocate additional pages within the reserved address space. You need to implement this behavior for each operating system though. For windows, lookup "VirtualAlloc". For Linux, look up "mmap". (Or generally: "virtual memory" / "virtual addresses")
CarlosMZ · 2025-02-08 05:53
I'm well aware that it's not the most impressive thing in the world (I am a long way from even being able to consider myself competent enough), but I'm very happy that I was able to come up with the solution without needing to watch a tutorial; just the language reference (the people who maintain cppreference are wonderful) and the Wikipedia article regarding the Caesar Cipher. I was really afraid I wouldn't make it, but I had a lot of fun while writing this small program and I even ended up remembering why I fell in love with computers in the first place. Criticism is more than welcome! Also, if you would like to take the algorithm and use it for personal purposes or even improve it, I would be more than honored by it. /* A small program that applies Caesar Encryption to encrypt an arbitrary word that is entered by the user using an environment-provided argument. Usage: executable [argument] */ #include <cstdlib> #include <iostream> #include <string> #include <stdexcept> int main(int argc, char* argv[]) { try { std::string plaintext = argv[1]; std::cout << "Plaintext: " << plaintext << "\n"; std::cout << "Please, set the encryption shift.\n"; std::cout << "(Tip: Negative numbers will invert the shift)\n"; std::cout << "|> "; /* I'm not going to lie: The intention was that negative numbers could not be accepted. But I ended up liking how it turned out, so I decided to leave it that way. Computers are funny. */ signed int shift {0}; std::cin >> shift; for (int letter_index = 0; letter_index < plaintext.length(); ++letter_index) { /* Subtract or add the decimal value of the ASCII character being accessed in the current iteration. [letter_index] indicates which character will be modified using the user-provided [shift]. */ plaintext.at(letter_index) = plaintext.at(letter_index)-shift; } std::cout << "Ciphertext: " << plaintext << "\n"; std::exit(EXIT_SUCCESS); } catch (std::logic_error) { /* If no argument is given, the program will provide the user with instructions on how to use the executable correctly. */ std::cerr << "Usage: executable [argument]\n"; std::exit(EXIT_FAILURE); } }
Chani · 2025-02-09 12:11
>>41134 A well written program and it does look like you had fun writing it! The program works well, but there are a few things I would like to point out. (1) On line 42, you are subtracting an arbitrary integer from a char. This can cause integer overflow which would result in undefined behavior. (Consider what happens if you subtract INT_MIN from 'a'). (2) If the shift amount is not big enough to cause UB, the program may still produce non-UTF-8 output. This isn't necessarily wrong, but it makes it harder to use the output (e.g. if someone wanted to copy the output and run it back through the program to reverse the cipher, some of the bytes might be discarded since they're invalid.) Most Caesar ciphers only rotate the alphabetic characters and leave the rest of the text as-is. (3) It is an odd design decision that the plaintext is passed as an argument, while the shift amount is passed through stdin. (4) On line 33, you declare letter_index as an int, but plaintext.length() could be greater than INT_MAX, which would result in undefined behavior when the program increments letter_index past INT_MAX. (5) If argc is 0 (which it can be on many systems including Linux), then you are performing an out-of-bounds array access on line 19. You cannot catch this as an exception -- it is UB. There are also some stylistic considerations which I won't comment on, but a handful of them do stand out. I don't know what compiler or operating system you're using, but if you compile with g++, you can use the -Wall flag to detect the issue on line 33 automatically. In general, I would recommend enabling most compiler warnings, as they will help you write more robust code and can even prevent some bugs before you even notice them.
Demeere · 2025-02-09 17:05
>>41134 >I was really afraid I wouldn't make it, but I had a lot of fun while writing this small program and I even ended up remembering why I fell in love with computers in the first place. Congrats lain! Good job. >Criticism is more than welcome! The biggest issue that stands out to me and wasn't mentioned by >>41140 is how you used the try-catch. A rule of thumb is that try blocks should contain as little code as possible. That allows more accurate error reporting, makes it immediately obvious to maintainers what line is potentially going to throw exceptions, conveys a clearer control flow, and (irrelevant to this case but worth mentioning) is less likely to result in exception cascading Your catch block comment says the try-catch is to handle then no arguments are provided, but using exceptions for that seems off since you can handle that by checking the value of argc at the start to confirm there's an argument, then exit if there's not. As other lain said >(3) It is an odd design decision that the plaintext is passed as an argument, while the shift amount is passed through stdin. And I want to elaborate on why: firstly, the shift is something the program needs and is simple enough that it is right at home as an argument. secondly, most programs that transform text will read the text from stdin because that allows piping and redirection from other programs (which is incredibly powerful), is less cumbersome for end users to work with for multiline input, and for sensitive input (like the plaintext of a cipher) means that plaintext doesn't need to be included in the command (and therefore stored in a bash_history file or similar)
CarlosMZ · 2025-02-13 00:59
>>41142 >>41140 Thank you very, very much for taking the time to analyze and review my code. I am completely honest when I say that the feedback provided is very valuable to me; I'm literally writing down all your comments. > It is an odd design decision that the plaintext is passed as an argument, while the shift amount is passed through stdin. I wouldn't call it odd, but rather unprofessional and a sign that I'm still a C++ newbie, ha, ha. The truth is that I was experimenting with the arguments of the main function and I did want to pass the shift as a parameter, but I had problems with the data types (transforming an integer type to a character type); I would even dare to say that it was lazy of me not to plan a more adequate solution to the problem. > I don't know what compiler or operating system you're using Yep, I use G++ on Linux (Mint). I will use -Wall from now on, thanks a lot for the tip! > for sensitive input (like the plaintext of a cipher) means that plaintext doesn't need to be included in the command (and therefore stored in a bash_history file or similar) I hadn't thought of that, you are so right. I will try to be more careful with those details in the future. I hope to serve myself as an example of what [b]not[b/] to do in cryptographic algorithms, ha, ha. Again, thank you very much for sharing your wisdom with me! And I hope that others who wish to improve their programming practices will also find it useful.
drop · 2025-02-19 10:47
This is a bit more C than C++ (although it still applies to C), but I recently discovered the joys of shoving like-data together into single-use structs like struct foo{ int bar; float baz; } foo; It gives you finer-grained control over memory layout, and as an added bonus, creates a kind of pseudo-namespace.
Anonymous · 2025-02-19 23:57
>>41251 Why would you even name your struct in this case?
Agent Richard Gill · 2025-02-20 10:10
>>41253 Unironically because I forgot that anonymous structs were a thing.
Boris Grishenko · 2025-03-05 11:52
It annoys me that C doesn't have any real generics. Having to maintain 20 different nearly identical functions and structs because I need more than one kind of linked-list is tedious, error-prone busywork with absolutely zero benefit. Even when I automate it with macros, which I frequently do now, it's still awkward. The only reason I use C++ over C is because of templates; otherwise, my code is as close to C as C++ can get. And it frustrates me, because it means my code is now significantly less portable. Anyone can implement C, but a C++ compiler needs a small country worth of people who've dedicated their entire lives to understanding the intricacies of that impossible fuarrrking language.
John Doe · 2025-03-05 22:16
>>41327 well, the reason for your woes ties back exactly to your needs. generics behave a lot like void pointers under the hood. abstracting them and letting an increasingly more complex and less portable compiler guide your hand doesn't really change what's actually happening in the computer. your real answer is probably to cut down on your need for so many types, though making your own for all your needs is definitely tempting...do that and your need for generics disappears.
Drifter · 2025-03-06 01:01
>>41329 >generics behave a lot like void pointers under the hood. Templates don't do that. They compile the same as if you wrote the function for each type. They're great although it can lead to massive code bloat if you abuse them.
Shogun · 2025-03-07 08:28
>>41329 >your real answer is probably to cut down on your need for so many types What I need is multiple versions of the same data structure that store different types. This is a much more common problem than you seem to think it is; one you encounter as soon as you need more than one kind of linked-list. Right now, my workaround is to use macros that generate the appropriate structs, typedefs, and functions for me, a needlessly complex solution that makes the code harder to follow than it really ought to be. Also, you're wrong. From what I can gather by reading documentation and looking at the Assembly output of my code, under the hood, generics, at least as implemented in C++ and Rust, work more-or-less the same as my macro-based approach, just with dedicated syntax and additional compiler optimizations enabled as a result of it being a first-class language feature.
pop · 2025-03-08 05:29
C++ templates is precompiler just logging every data type you replaced <class T> with and then copypasting same code replacing "class T" with int/float/myclass/... for every version you used. You use 10 data types you get 10x code. I don't think the compiler does any smart optimization off this. Maybe it changed but the general problem is type safety Generics have also a catch- a generic function doing "return a+b;" means myclass has to implement +operator for itself to make a+b work inside the function. Modern C++ uses Iterator as the universal connector. Everything builds on Iterator to make sure implementing Iterator is enough to use standard library functionality with your custom classes. If you got a custom data structure and implement iterator your data just needs to have < defined to access all sort algos. That's the point of it. --------------- That aside imo other guy was right about using void* in C. Note there is no cost of "casting void pointers" in C because you dont actually cast. int* intP = voidpointer is just copying the memory address so you can threat whatever is stored at the void pointer as a int. This is something exclusive to C that's forbidden in C++. That's why you can abstract in C with void* and simply use pointer conversion different to C++. You dont need templates in C because pointers are inherently generic and "type safety" isn't obstructing you like C++ does. I.E. you can make a {void*, int score} struct array with void* pointing to any data and score being some score function output for the data to define an order for your data. With this you dont have to care what void* points to, you just sort the array by int score and get the order of void* as a result of it. Defining a score function for each data type would be equal work as defining "< operator" for every data type in C++ and you could extend it to {void*, int score, enum dataType} and use the same approach to sort mixed data types because you would still only be comparing int without care what the void* points to. The same approach can be used for storing data - make the score function a hash function and you can implement a generic hashmap around a {void*, int score} struct. If you want something simpler you can implement a <vector> equivalent as a simple void* array with int elementsStored and arrayLength.
XERXES · 2025-03-08 06:08
>>41333 >What I need is multiple versions of the same data structure that store different types. What I need is multiple classes of the same class that store different types. Sub-classes based on parent perhaps?? i.e. Inheritance, (and/or overloading the constructor on the parent class). Using a struct sounds painting a wall with a toothbrush, where wall = problem and toothbrush = struct.
Hong, Guil Dong · 2025-03-08 06:18
>>41336 C doesnt do classes
dup · 2025-03-09 11:37
>>41335 Wouldn't that require some kind of switch-over-type? I would figure that would have a much bigger performance impact than any code bloat that could result from my macro method, not to mention much more annoying to maintain.
Neo · 2025-03-09 16:20
>>41341 Its naturally much better for performance to separate data by its type into different lists. The mixed data with enum idea was just a gimmick howto mimic C++ OOP in C where you mash different classes into one structure and then loop over them all in one go. Could do that with a switch statement on the enum or an array of function pointers where func_array[enum_datatype] would access the right function call. I think in general performance doesnt matter for most hobby projects. Your time is the actual limit which is why things should be done in most efficient matter. If its easier to write and maintain then its good.
Eldon Tyrell · 2025-03-10 17:54
I've been trying to avoid code comments and instead writing "self-documenting code", but I've reached the point where I don't think that's really feasible once a project hits a certain size, at least not in C/C++. Sooner or later you're going to write a function or design a class that has too much going on in it for a quick glance to suffice. So I've taken to describing what every nontrivial function does and what every nontrivial class does with a comment at the top of its definition. And before anyone says it, no, decomposing them into smaller classes and shorter functions doesn't help. If anything, it makes the problem worse, since now the actual guts of your classes and functions are scattered across your codebase.
Case · 2025-03-11 04:05
>>41349 self documenting code is advice meant for the beginner programmer documenting every line or documenting nothing and naming everything like its encrypted. Its never telling you to not document what your modules do. The whole point of modules is not checking whats inside. You just read what it does and how to use it which ideally is documented.
BloodCat · 2025-03-11 16:14
Is there a way to completely prevent implicit casts in C/C++? They are the absolute worst part of both languages and a fuarrrking retarded design choice with no justification
hash table · 2025-03-12 11:11
>>41357 What the hell are you on about? First of all, I'm asking the language to be more explicit, not less. I want to put every conversion in my code manually, so that I know when and where each of then happens. What you're doing is paramount to calling me a pussy for wanting to use explicit type annotations instead of auto. Also, so? It's not like it costs me any performance. There's genuinely zero runtime cost to explicit typing. Why you think I should do things the hard way even though it's of zero benefit to me is a mystery. >not using auto on everything would help too I don't.
HELIOS · 2025-03-13 00:29
>>41363 you doing things the hard way trying to make more work by insisting on explicit casts. I cant imagine anything more annoying than having to do "0.f" instead of "0" because you need to be explicit whether your zero is float or int. And the original take was the only reason to not understand an implicit cast at a glance is type obfuscation which in C++ happens due auto.
The Phantom Phreak · 2025-03-16 08:36
Some jobs I look at have requirements like "advanced C++ skills" but don't elaborate further other than job specific things which aren't C++ necessarily (e.g. networking). I'm looking for a type of project that can be used to gauge my skill level, particularly a project that would be widely considered advanced so I can use that as a reference regarding where my abilities are at (and so I have a concrete goal to work towards of course). What would you say said advanced project would be? I thought of something like a torrent client, that requires concurrency, UI, networking, some optimization so as to not have atrocious performance... But generally when I think of an advanced project it seems specific to a certain area (which is expected to some extent). For example, the torrent client might be useful if I'm eyeing a networking position but not so much for others.
Dr. X · 2025-03-17 08:50
I've been looking through the things C17 and C23 add to C, and I'm kind surprised that neither of them added proper filesystem abstractions into the stdlib. A lot of the stuff they did add, however, looks like nonsense to me. As far as I'm concerned, C, as a language was 90% complete with C99. The remaining 10% is stuff relating to cross-platform compatibility. I shouldn't have to include ifdefs for every platform in user-space code. But for whatever reason, nobody else seems to care.
Colmerauer · 2025-04-29 03:46
Are there many junior c++ jobs in the USA? Everyone I know works in web dev but the only open source repos I'm interested in are written in c++. I can't imagine contributing to any python/ts/java repos without being paid an absurd amount of money and possibly working from home. I originally got into CS because I thought certain projects were cool such as qbittorrent and pcsx2 which were both in c++. I'm having trouble justifying spending time on c++ when it seems like I'm going to be forced to write react/node/insert web framework here for money. Basically I'm afraid of getting laid off and then the interview doesn't give a fuarrrk about any of the CS fundamentals or c++ I studied or emulator domain knowledge or low level networking I learned because it's not X YoE in {front end framework} or java spring. I already work full time and my job is chill enough to learn c++ in the downtime and I can occasionally work on tasks related to c++ every couple months but I'm mostly typescript for now.
Wirth · 2025-04-29 14:10
>>41949 I don't know about the US, but here in the UK they do definitely exist and for the company i work for it can even be hard to find good c++ devs. I think you do have to get lucky location wise, the jobs I've had have been on-site only and at more industrial locations due to the nature of what they do. Do a bit of research about companies in your local area that do work with machinery, robotics, automotive, etc etc. this is where c/c++ jobs are hiding. For my current job I did exactly this and sent an email to the CEO (small company) and got an interview literally the next day. Wouldn't have happened if I didn't do the digging myself. Really though if it's what you're interested in, stop doubting it and just do it. The skills are transferable mostly anyway
Nameless · 2025-04-29 16:01
>>41026 >>41026 Yeah, you're right. I started on learning c++ in earnest today. Thanks!
Roy Batty · 2025-04-29 20:11
When do you know its time to learn C, C++, C# after getting gud with python?
Lord Nikon · 2025-04-29 23:00
Why do you feel like you need to get good with python to learn C? Btw, despite the similar names, C, C++ and C# are very different
typedef · 2025-04-30 14:57
>>41959 to be fair C and C++ have a significantly higher overlap with each other than with C# or Python. C++ isnt exactly extended C but it does retain a lot of the syntax (even if its partially fake like structs arent real structs but public classes if you add a constructor) but +1 for you dont need python to learn C and vice versa, it wont help you at all in fact because aside from very basic things like "whats a loop" there is not much overlap. The syntax and way of thinking is entirely different.
Judge Fang · 2025-05-01 19:41
Suppose I mess around with C++ while I study CS fundamentals for 2 hours out of my 8 hour work day and make open source contributions for 3 years at a job where I actually write another language. Should I just lie and say I have 5 YoE and did this at my previous job to get past ATS/HR? From my experience with other languages there is no substantial difference between good code written for a company and good code for a side project or open source. Often times the open source repos are superior. Just not sure if this is true for C++ yet. It seems if I can't do this it's not really worth it for me to ever do C++ professionally, because I'll have 6 years of typescript exp + cloud and entry level big tech SWE jobs pay more than senior C++ ones near me.
Mentat · 2025-05-08 11:54
>>41987 I did some research into this subject. I'll share some advice I got and what I found for people who maybe have the same question. It taught me quite a bit about getting a software development job. My first job I got with no referral, I didn't realize how important they were. 1. Always try to get a referral, particularly when swapping stacks like this 2. If you are good enough to do the job, have a referral, and HR might block you due to YoE in a stack, just say you did that stack on your resume 3. There are very few C++ jobs related to back-end around where I am 4. What embedded jobs there are, generally pay a lot less than back end + cloud near me. This field generally requires people to hire you and train you for quite a long time, along with knowledge that takes quite a while for a generic back end dev to acquire 5. There are almost no high performance computing or high frequency trading jobs near me
John Titor · 2025-06-09 10:06
I have been learning c++ on my own my current path to learn it is the following: >A Tour of C++ by Stroustrup >Understanding and Using C Pointers by Richard Reese >C++ Software Design by Klaus Iglberger Anything else I should be reading?
Fred Nurk · 2025-06-09 10:09
>>42333 >Understanding and Using C Pointers by Richard Reese If you're using modern C++ properly then you won't be using pointers.
Neo · 2025-06-09 10:12
>>42334 I will be working on a project that isn't as modern and the code has a soykaf ton of functions with pointers in the parameters and return values, so yeah I will have to.
John Doe · 2025-06-09 20:40
>>42334 I've seen code where an object owned by a std::unique_ptr gets passed by raw "C-style" pointer to a stateless helper function by using the unique_ptr's get(). Since the helper function doesn't affect the ownership of the object, this is considered preferable to piling on extra complexity to switch to using std::shared_ptr. StackOverflow answer that mentions this use-case: https://stackoverflow.com/a/9699490
Linda Lee · 2025-07-01 13:35
I know I've said it before, but it frustrates me to no end that C++ is so massive. Using it instead of C means that my code is automatically much less portable for very little gain, since I use a very small subset of C++'s features and virtually never touch the STL at all. But at the same time, going with pure C means I miss out on a lot of genuinely useful things, like classes, templates, operator overloading, RAII, etc. It's not unworkable, and I often end up going with C instead for that reason, but it's a lot clumsier and uglier. Whenever I'm using one I feel like I ought to be using the other.
Nell · 2025-07-01 13:44
>>42508 In what usecase is C++ less portable than C? That aside i believe everyone is just using a subset of C++. Google as a big corpa example has C++ guidelines that limit their coders to a sane subset which is more easily to read&maintain.
Kay · 2025-07-01 13:48
>>42509 There should be specific tutorials or books on specific subsets of C++. That'd make learning the language way easier
Ivan Petrov · 2025-07-01 14:15
>>42510 Universities curate a sane subset in their C++ courses. Another subset category is simply the C++ standard, C++11 has a much smaller footprint at the price of being less convenient in syntax. If you take the newest standard it holds comfort updates but you have to also deal with bloat of new functionality you don't need. That aside as previous post mentioned google, apple, etc. publish their own standards, you can learn their style without being an employee.
list · 2025-07-01 22:11
>>42509 It's significantly harder to implement. You can write a C compiler on your own. Good luck doing that with C++.
The Oracle · 2025-07-16 10:14
What the fuarrrk is Jon Blow talking about when he says that RAII causes cache misses? As far as I'm aware, all RAII is just acquiring resource with a constructor and then releasing it with a destructor when it goes out of scope. It's such a simple, broad approach to resource management that I'd independently discovered it myself and had been doing it in C for years with functions like init_data_structure() and destroy_data_structure() , not even knowing that the technique justified let alone had a name. Is there something I'm missing about the way C++ does it, or is Blow just talking out of his ass?
Dox · 2025-07-16 11:25
>>41026 > Is it possible to get a job using C++ as a beginner? Nope. > In which projects is C++ most commonly used these days? None that matter. > Do I need to know a lot about low-level programming? U shouldn't program in C++.(USER WAS WARNED FOR THIS POST, You should always elaborate on your opinions rather than just spilling the soykaf.)
Mentat · 2025-07-16 12:11
>>42614 He's probably advocating using memory arenas, which isn't really compatible with RAII beyond writing a destructor for the memory arena itself. You can ask Deepseek what are the pros and cons of memory arenas in C++, it should explain better than I can and I'm too tired to go into detail. Allocating everything in heap at once at program launch in a so-called memory arena/pool is less likely to be fragmented in RAM (therefore potentially less cache misses) instead of allocating data structures individually throughout program runtime which is more likely to be scattered in RAM (therefore potentially more cache misses).
drop · 2025-07-16 14:53
>>41026 embedded uses C/C++ because C is still the best for embedded and C++ attaches well. Outside of that anything that needs performance writes C++ so Unreal Engine for gaming in example. That said gamedev jobs are notorious trash. gpu programming opengl / cuda languages are also just C++ variants in syntax.
Void · 2025-07-16 22:23
>>42614 The problem is when you have destructors that call destructors that call destructors... It ends up being like tracing garbage collection, jumping around all over memory, jumping from task to task instead of doing everything all at once.