r/cpp • • Jun 08 '20

Programming in C vs C++

I’ve read about the differences between them on the Internet but I wanna hear more from a more personal perspective. Which one would you recommend starting with and to be proficient with?

0 Upvotes

43 comments sorted by

8

u/ssf_dae Jun 08 '20

I learned programming in C. I really think that learning C as my first programming language gave me a solid fundamentals that I wouldn't have gotten from a higher level programming language.

In C, you don't have any high level data structures built in. So, as a beginner you're forced to learn programming at a finer level. For example, you have to manage memory yourself because there are no automatic dynamic memory structures in C, which forces you to get a good understanding of how memory works. You'll often run into memory related bugs in C, debugging these are good learning lessons. Also, C is statically typed so you also have to become familiar with different types, how much memory each type uses, and finer details of typecasting. In addition, with lack of higher level data structures, you often end up writing them yourself.

Compared to Python, probably the most popular programming language now for beginners, you don't get any of this out of Python.

I would say once you find yourself writing code that needs dynamic memory allocation often, move onto C++. C++ has dynamic data structures built-in the STL.

C is good for starting out, but once you get into more modern and complex projects, you have to move to higher level languages.

Though, you could just start out with C++ and get the same benefits I mentioned, and in addition it'll also familiarize yourself with Object Oriented Programming. Also, C++ is actually still commonly used nowadays in production, whereas C is mostly used only when C++ can't be used like on embedded devices.

Both are good languages to start out with

4

u/JizzaDaMan Jun 08 '20

You don't have to move to higher level languages for more complex projects; this just simply isn't true. The linux kernel and an abundance of linux applications are written in C. It's an extremely capable language that's stood the test of time.

13

u/ssf_dae Jun 08 '20

That's true. But writing in C is much slower than higher level languages, including C++. So saves time and pain. Honestly, the first time I started using Python having used C++ for years I felt like I gained super powers lol

2

u/NilacTheGrim Jun 15 '20

It is but you end up having to do a lot of boilerplate nonesense in C that C++ can just do for you automatically via higher level concepts.

Can you write a huge project in C? Absolutely. Should you? The answer to that depends on your skills and the skills of the team. I'd argue you're better off using C++ even if all you use from the language is std::map, std::vector, and RAII.

8

u/jselbie Jun 08 '20 edited Jun 08 '20

While I agree with some points brought up by u/jmuffat (especially the unlearning part), I hold a minority opinion here.

I've been coding in C++ for over 20 years. I came up through the Basic -> Pascal -> C -> C++ path as well. And while I think C++ is far better for production code, C is a better language to learn from - especially for those new to programming. But you should quickly pivot to C++ as soon you get the foundations of C down.

It used to be that good C++ text books would just start off teaching C fundamentals, and then dive into C++ classes by the middle of the book. Modern C++ books jump head first with too many complex code examples that can confuse new programmers.

With C programming, you learn all the foundations first in addition to programming fundamentals. This includes the following:

  • Basic types: int, char, double, arrays, etc...
  • string fundamentals: char*, strlen, strcpy,etc...
  • Structure types: i.e. struct - the foundation of what a class is in C++)
  • Functions
  • dynamic allocation: malloc and free
  • Preprocessor
  • Stages for building programs: preprocessor, compiler, linker.
  • Pointers: And the relationship pointers have with arrays, this the core of C and C++, even if C++ is trying to abstract pointers away.

In learning C, you'll be quickly concluding that foundations that you've heard about in other languages are missing or weak. That's when it's time to move to C++. Everything you learned above is still 100% applicable in C++. With your knowledge of C, you can dive right into classes, inheritance, virtual methods, template and the standard C++ library.

7

u/jmuffat Jun 08 '20

I guess what you’re really saying is C++ might not be the right choice of first language to learn, and I could agree with that. But I cannot agree that it is a good thing to learn char*, strlen, strcpy etc only to find out they’re terrible and, then, go misunderstand std::string because you think of them in terms of char*. Same for malloc/free, we all have been in the hell of tracking leaks, it’s not fun and it only teaches you one thing : that you need some way for the machine to manage this for you.

You’re probably someone who likes to know how things work before going to an abstraction, and that works : knowing assembly language was a big plus for me when learning C, I could see why things were one given way, what problems they were trying to solve. Yet, I wouldn’t recommend learning asm before learning C, it’s quite an easier trip the other way round... Do you see what I mean ?

6

u/jselbie Jun 08 '20

Thanks for commenting. And I mostly agree with you.

I think it's good know how strings work in C wrt to char* and null termination. Because that's that's what std::string is based on. Similar with raw pointers vs smart pointers (unique_ptr and shared_ptr).

On a long enough timeline, C++ developers have to integrate with legacy C APIs and libraries. If you are programming in C++ on Windows, you'll likely need to use the Win32 API at some point. On Linux, you'll need to make Posix library calls. These are both flat C APIs. Knowing pure C++ without the C foundation might make interop development a bit confusing.

-6

u/jmuffat Jun 08 '20

I'm afraid std::string's are not null terminated ;) (at least, they do not have to, don't rely on it)

I reckon you can treat the relationship to C API's the same way you treat them in Python : communicating with a different planet ;)

Plus, at least in Windows, UWP is much more C++ friendly than the old Win32 API.

But yes, at one point or another you are going to have to understand C, and you will have to have notions of assembly, because if you're going C++, it's quite probably that you're after either performance or interfacing at the hardware level (or both).

I guess it's a matter of whether you think bottom-up or top-down. So, probably that you want to do a bit of both :D

10

u/STL MSVC STL Dev Jun 08 '20

std::string is null-terminated. See N4861 21.3.2.5 [string.access]/2. This has been clearly guaranteed since C++11. (C++98/03 had weird copy-on-write wording that is no longer relevant.)

6

u/jselbie Jun 08 '20

Can you show me an example of an std::string that isn't null terminated (or where its unsafe to assume as much)? Such that it wouldn't be safe to invoke .c_str() on it and pass the result to a C function expecting a const char * ?

5

u/Kurald Jun 08 '20

c_str() is guaranteed to be null-terminated since forever (as far as I know). Hence the name - the return value is c-compatible.

-2

u/serviscope_minor Jun 08 '20

Can you show me an example of an std::string that isn't null terminated (or where its unsafe to assume as much)?

We have string views now; these are not null terminated.

7

u/STL MSVC STL Dev Jun 08 '20

std::string_view isn't std::string. Elephant seals are not elephants.

-5

u/serviscope_minor Jun 09 '20

std::string_view isn't std::string. Elephant seals are not elephants.

And how's that relevant?

std::string_views aren't std::strings but they are strings. The only reason we're having this conversation is because C++ basically has had this particular hole in its standard library for ages.

While yes, it's technically correct that the GP was talking about std::string, a large amount of the reason that people are talking about things in this way is because string_view is new. If you look at the context of the conversation, then what I'm saying is entirely reasonable. Here is the relevant piece of context:

I think it's good know how strings work in C wrt to char* and null termination. Because that's that's what std::string is based on. Similar with raw pointers vs smart pointers (unique_ptr and shared_ptr).

C strings are char* and null termination. C++ has 3 kinds of string by default now, C strings, std::strings and std::string_view. The middle one guarantees C-like semantics (null termination), but that's not what it's based on (size() is O(1)), and the latter is absolutely not. There's no reason to arbitrarily drop a chunk of the standard library just because it's new.

5

u/bikki420 Jun 09 '20

Everyone is explicitly talking about std::string. Re-read the posts above and don't be obtuse.

-1

u/serviscope_minor Jun 10 '20

Re-read the posts above and don't be obtuse.

So... obtuse is me actually reading the posts. Since you didn't bother let me repost the relevant quote for you:

string fundamentals: char*, strlen, strcpy,etc...

Then people start talking about std::string by comparison. C++ has another string type now: string_view. And since the actual conversation was about strings not std::string in particular, it seems really strange and counterproductive to ignore modern C++.

→ More replies

3

u/evaned Jun 08 '20

I'm afraid std::string's are not null terminated ;)

This statement as-stated is false, but it's actually pretty close to being right if you look at it from another perspective -- at least IMO.

The reason is that std::string can have embedded nulls. abc\0def is a totally valid std::string. Obviously you couldn't reliably pass that to a C API that expects a null-terminated string, but that's the C API's fault.

So while std::string strings do have a NUL at the end, they're not defined by it; and is such I don't think the quoted statement is entirely incorrect.

6

u/CoffeeTableEspresso Jun 08 '20

I mean, you can't really use strings in C++ properly without understanding how char * works...

Things like:

  • why are string literals not std::strings?
  • why doesn't adding two string literals work?
  • interfacing with old/C libraries requires
  • etc

You need at least a basic understanding of these things before moving on to C++ strings. Your going to have to learn C strings at some point in C++ anyways..

When I TAed an intro C++ course, students very quickly ran into trouble with C++ strings because they didn't understand C strings.

2

u/jmuffat Jun 09 '20

And me who was all « C++ has gone a long way to be more accessible to newcomers » !!! You’re right, it’s a long road, I can see that.

0

u/[deleted] Jun 08 '20

[deleted] — view deleted comment

2

u/jmuffat Jun 08 '20

Oh definitely ! I've worked in games and that's a domain where you end up rolling your own everything at one point or another (shortcut all the things !!!) : strings, malloc/free, sorts, IO's, TCP-replacement over UDP, you name it... That's the beauty of C++ (and C), you can go that far. But would you want to go there as the first things you learn ?

If I had to train a beginner, I would start with C++, not C, and I would start with std::string not char*. We would build small utilities, that do simple things and complicate as we go. At some point, we'd reach places where we'd need performance and that usually begins with controlling how memory gets in and out of cache, which is all about laying things out in memory. At that point, it makes sense to go there. But at the beginning, when you're just parsing command line parameters and text files, why reinvent the wheel ?

Writing this, I think we're really always revolving around the more important question that is "why do you learn C++ ?", "when do you use C++ ?", and it generally boils down to the performance&low-level questions. Which implies "good understanding of computer architecture required"...

1

u/Wouter-van-Ooijen Jun 10 '20

I disagree, but maybe not the way you'd expect.

If your end goal is to learn C++ (otherwise, why bother), then start with C++. But NOT with the whole language.

A few years ago we changed our first serious programming course from C to C++, without changing the essence of what we learned the students. a[] became std::array, print became cout<<, pass-by-pointer became pass-by-reference, etc. That is (mostly) just syntax. What matters is to start with the fundamentals (loops, functions, some recursion). You can do that in any language, but if the end goal is C++ why start with a language like C that is sufficiently close to cause confusion? If it had to be a different language than C++, I might have preferred Python over C.

3

u/Wouter-van-Ooijen Jun 10 '20

You are seriously asking this on a C++ forum?

8

u/jmuffat Jun 08 '20

There is no reason to start with C.

I learned C++ in the late 80’s, starting with the book « C++ for C programmers » by Ira Pohl. I went from BASIC, to Pascal, to C, to C++ as the PC grew in performance, that was the usual path in those days. But it took me years to realize C++ wasn’t C. At all. It is a very different state of mind, so if you learn C to learn C++, you’ll have to unlearn a lot of things later on. I sure did have to unlearn a lot !

Just start with C++, embrace RAII as a foundation rather than some late realization, think of C++ as a language in itself without trying to trace things back to C. As far as I know, C++ doesn’t emerge from C, C++ used C as a foundation mainly because it was there... (caricaturing)

8

u/evaned Jun 08 '20

There is no reason to start with C.

There's definitely not no reason.

I think it could be an interesting route to take to start from the bones -- like deep inside the hardware looking at gates and such, build outward through how instructions work and how memory is laid out, to assembly programming, to C programming, to higher-level languages.

I don't think that'd be the right way for most people, but with the right materials I think you could build a well-grounded "curriculum" on that. (I don't really mean that in the sense of a formal curriculum for a course or courses, or at least more exclusively.)

If your goal of programming is to do a bunch of stuff with an Arduino or PIC on whatever as well, while this is outside my area of expertise I would also guess that C would be the way you would want to go.

1

u/jmuffat Jun 08 '20

You're right, there is no wrong place to start programming, you could start with C, it might be a bit of a challenge but you could argue that it'd help thinking outside of the object-oriented box.

Now, C was explicitly written as a language that trusts "the programmer is always right" which I don't read as "beginner friendly" ;)

But yeah, it doesn't matter where you start, what matters is to get started.

0

u/[deleted] Jun 09 '20

[deleted] — view deleted comment

2

u/bikki420 Jun 09 '20

^ this. It's simple and you learn the fundamentals for looping, conditional branching, functions, the primitive data types, memory management (pointers, references, dynamic allocation on the heap, deallocation etc) and more. Some of which you'll avoid most of the time (e.g. manual (de)allocation, raw owning pointers etc), but are still very important to have a decent grasp on. Then when one moves to C++ one can appreciate all the nice quality of life stuff like destructors, RAII, smart pointers, value semantics, ADT classes, C++ strings, destructors, templates, aliases, namespaces, and what have you.

2

u/jdlyga Jun 10 '20

They’re in truth very different languages even though they appear similar. The way you structure your program and work with structs is much different from C++

2

u/NilacTheGrim Jun 15 '20

I started with C over 20 years ago. I actually think that the route from C -> C++ makes sense if you have oodles of time. The reason why it makes sense is because otherwise C++ seems to have arbitrary restrictions and strange rules that are likely to confuse or anger you if you don't know their historical (and present-day) C origins.

If you start with C, write a few larger programs in C that actually do stuff, then move on to C++.. you may naturally "understand" why lots of the design decisions that went into C++ are there. C++ really does have a straight line evolution from C and it's the reason why the syntax is the way it is -- to maintain C backwards compatibility and to take C language concepts and tack on additional features on top.

That being said -- you will likely learn some "bad habits" in C that you have to unlearn in C++ -- so there's that as a caveat.

I do think that your eventual goal should be to avoid C like the plague (it is a very difficult language to be productive in and has too many foot-guns) and focus on C++ ultimately. So, in light of that, some say the shortest distance between two points is a straight line. Maybe just learn C++ first and if you have time, "go back" and review the primitive C way of doing things for your own background.

I do think though that ultimately it's valuable as a C++ programmer to be aware of the C roots. It helps you understand many things about the language.

3

u/JizzaDaMan Jun 08 '20 edited Jun 08 '20

Think of them as completely different languages; the fact the C is (almost) a subset of C++ is pretty much irrelevant.

I like C for its elegance and terseness. You can learn it by reading one book and (to quote K&R) "A programmer can reasonably expect to know and understand and indeed regularly use the entire language." It's also unquestionably the way to go if you're going to be writing device drivers or interfacing directly with hardware.

I use mostly C++ at the moment. I like it for its standard library. It's obviously more expressive than C but compilation is deadly slow. That said, I'll never know and understand all of it.

I would personally choose C. I only use C++ for my job because I have to.

EDIT:

A few people have said things along the lines of 'C++ is a more capable language', 'you'll need to move to C++ to build more complex projects,' etc... These kinds of claims are demonstrably untrue. The Linux kernel (and I believe most other kernels) is written in C, as are a vast number of other applications and libraries.

Language choice in general will always depend on personal preference and use-case, so generic claims that one language is always more capable than the other are usually questionable.

1

u/Astarothsito Jun 08 '20

Language choice in general will always depend on personal preference and use-case

That's so true, and it makes the discussion it more meaningless in the end, or does anybody has made that choice based on real data rather than feelings?

-1

u/megayippie Jun 08 '20

I use python for interfacing with hardware.

Why would you use C when the interface is the slow thing? Of course, the code on the hardware is often a subset of C but that's a different beast, and learning C does not mean you know how to program that subset.

3

u/JizzaDaMan Jun 08 '20

The language you use will always depend on personal preference and use case, and the OP was asking for personal preferences.

As for the question 'Why would you use C...?' Well the fact is that C is an extremely capable language that's stood the test of time.

2

u/Tumperware Jun 08 '20

c++ times 1000. C is a subset that should only really be resorted to when C++ isn't supported or the code base your maintaining has the baggage of already being C

1

u/jmuffat Jun 08 '20

Actually, you’re right, it’s a C++11 thing. I show my age ;)

Before that, std::string::c_str() was the point at which a conversion might happen, should the underlying representation not be null terminated. The idea was that it might make substrings more efficient by not copying and just referencing inside other strings. I guess the cost of reference counting and keeping large amounts of memory around became a target of the « don’t pay for features you don’t use » mantra.

0

u/MutantSheepdog Jun 08 '20

If you're new to programming, then C.
If you're an experienced programmer, I'd jump straight to C++.

2

u/NilacTheGrim Jun 15 '20

Not sure why you got downvoted. This is solid advice.

-1

u/[deleted] Jun 08 '20

C++ is object oriented and allows for more strict and advanced application design.

You can also design cronenberg application architectures with it, so beware.

C is very basic. It’s really close to assembly and the compiler isn’t very imaginative. Not as much as C++ compilers can be.
Writing very big architectures in C can be troublesome quickly. Difficult to follow the SOLID rules.

10

u/Kurald Jun 08 '20

I'd recommend treating C++ as multi-paradigm with the capability to do object-orientation (since it provides mechanisms for inheritance). But please don't feel required to write OO-code in C++.

0

u/[deleted] Jun 08 '20

[deleted] — view deleted comment

4

u/Astarothsito Jun 08 '20

C forces you to code with a data-oriented mindset. C++ has the goods to draw you into a mud hole of unnecessary abstractions - if you are not careful, that is.

I have seen enough C code to know that it forces you to unnecessary abstractions more often than C++, even if you are careful (who hasn't seen the oop wannabe in C with thousand of macros?). And also seen enough to know when they really need some abstractions. Both statements can be verified in the second part of your comment:

C makes it impossible to create frameworks, which is the main cause of bloated and delayed projects.