15

I know that C++ has the concept of objects but C doesn't. I also know that pretty much all there is to know about C fits into K & R but the C++ library is vastly more complex. There have got to be other big differences though.

What are the major differences between C and C++?

Dinah
  • 52,922
  • 30
  • 133
  • 149
  • 21
    The "++"-part... :P – Ward Werbrouck Mar 12 '09 at 21:59
  • You don't think those are major differences? – Trent Mar 12 '09 at 21:59
  • 1
    @Trent: I do but is C++ merely C with objects and a bigger book? If so that answers my question but I've always gotten the impression that there was more to it than that. Perhaps I was wrong. – Dinah Mar 12 '09 at 22:01
  • "merely" would be a huge understatement of OOP versus procedural. Its like saying "functional" is "merely programming without states." Ok, maybe not that big. – bdd Mar 12 '09 at 22:04
  • wow.. why wasn't this closed, or community wiki. – sfossen Mar 12 '09 at 22:10
  • This question appears to be off-topic because it is about **really?** –  Aug 22 '14 at 22:48
  • The C and C++ standards both define the word "object" in a manner that has nothing to do with object-oriented programming (OO); in both, an "object" is just a region of storage. C++ does have additional features to support OO. It's also important to be aware that C++ is not entirely a superset of C; it's easy to write valid C code that's not valid C++ code. – Keith Thompson Aug 22 '14 at 23:05
  • 1
    this question is not related to - a specific programming problem, or - software algorithm, or - software tools commonly used by programmers; and is - a practical, answerable problem that is unique to software development (http://stackoverflow.com/help/on-topic) – BlackBear Aug 23 '14 at 00:51
  • I've added [a more or less definitive answer, based on the C++ standard](http://stackoverflow.com/a/25456680/464581). It's noteworthy when a question that has a definitive answer in an ISO standard, is closed as too broad. Please, when voting to close out of ignorance, on the grounds that you yourself don't know any definitive answer, belay that action: do consider whether your inability stems from competence (do vote) or incompetence (abstain from voting, please). – Cheers and hth. - Alf Aug 23 '14 at 10:14

11 Answers11

31

The C++ language says they are the same:

int C = 0;
assert(C++ == C);
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
  • 1
    Apostles of K&R know the prescience of this statement. – hyuan Mar 12 '09 at 22:13
  • 11
    lol That's not true though. The result of your equality test is undefined... :) I wonder what that says about the two languages. :p – jalf Mar 12 '09 at 22:34
  • 3
    gcc and vc++ both say it's true – Brian R. Bondy Mar 12 '09 at 23:27
  • 3
    @jalf: Not just the result; the *behavior* is undefined. – Keith Thompson Aug 22 '14 at 23:05
  • 1
    I prefer this version: `int C = 0; assert(C++ >= C);` – Spire Aug 23 '14 at 00:54
  • You can refer here: http://www.preprogrammer.com/all-the-major-difference-between-c-and-c/ –  Jun 22 '16 at 07:48
  • @KeithThompson Could I ask why is this undefined? Also, what's the difference between 'undefined result' and 'undefined behavior'? (I only know undefined behavior) – starriet Aug 22 '22 at 01:43
  • 1
    @starriet The behavior is undefined because the evaluations of `C++` has the side effect of modifying the object `C`, and the subexpressions `C` and `C++` are unsequenced. The language doesn't define the term "undefined result". – Keith Thompson Aug 22 '22 at 02:50
  • Indeed the assert *fails* by gcc and clang. MSVC compiles it true. (Please let me know if the results are different for different compiler versions) – starriet Aug 22 '22 at 04:11
26

Check out Stroustrup's FAQ here, specifically:

What is the difference between C and C++?

C++ is a direct descendant of C that retains almost all of C as a subset. C++ provides stronger type checking than C and directly supports a wider range of programming styles than C. C++ is "a better C" in the sense that it supports the styles of programming done using C with better type checking and more notational support (without loss of efficiency). In the same sense, ANSI C is a better C than K&R C. In addition, C++ supports data abstraction, object-oriented programming, and generic programming (see The C++ Programming Language (3rd Edition)"; Appendix B discussing compatibility issues is available for downloading).

Andy Mikula
  • 16,796
  • 4
  • 32
  • 39
  • Refer here for complete details : http://www.preprogrammer.com/all-the-major-difference-between-c-and-c/ –  Jun 22 '16 at 07:53
17

I think you answered your own question: Classes

Its a completely different design paradigm. I think the confusion comes because many people develop C++ programs that are basically C programs and don't even realize it.

Which allows, in the word of its creator, Stroustrup:

Edit: added some other fun stuff

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
bdd
  • 3,436
  • 5
  • 31
  • 43
  • 1
    Upvoting because of "...many people develop C++ programs that are basically C programs and not even realize it." – overslacked Mar 12 '09 at 22:01
7

C++ is mainly an extension of C. Originally C++ was called “C with classes”, highlighting the main original language extension. Already at that time overloading of functions was supported. Since then C++ has acquired exceptions, hierarchical namespaces, generic programming in the form of templates, and lastly multi-threading support. As of C++11 there’s also some minimal core language support for garbage collection using e.g. the Boehm garbage collector. Smaller extensions include reference types, trailing function return types syntax, memory allocation and deallocation machinery that can be overridden, run time type information, and more.

The differences between C and C++, i.e. between C and the “C subset” of C++, are summarized in the C++11 standard's appendix C, entitled “Compatibility”, which is about 20 crammed pages, where the C1 section that pertains to C compatibility is about 10 pages.

It was appendix C also in C++98 and C++03, and it’s appendix C also in the fresh new C++14 standard.


As of C++11 appendix C of that standard lists the following incompatibilities between C and C++:

§C1.1 Lexical conventions

New keywords (§2.12)

The paragraph only refers to C++11 §2.12. The following list was generated from that table and a corresponding table in C99.

    C99                 C++11

    _Bool               
    _Complex            
    _Imaginary          
                        alignas             
                        alignof             
                        asm                 
    auto                auto                
                        bool                
    break               break               
    case                case                
                        catch               
    char                char                
                        char16_t            
                        char32_t            
                        class               
    const               const               
                        const_cast          
                        constexpr           
    continue            continue            
                        decltype            
    default             default             
                        delete              
    do                  do                  
    double              double              
                        dynamic_cast        
    else                else                
    enum                enum                
                        explicit            
                        export              
    extern              extern              
                        false               
    float               float               
    for                 for                 
                        friend              
    goto                goto                
    if                  if                  
    inline              inline              
    int                 int                 
    long                long                
                        mutable             
                        namespace           
                        new                 
                        noexcept            
                        nullptr             
                        operator            
                        private             
                        protected           
                        public              
    register            register            
                        reinterpret_cast    
    restrict            
    return              return              
    short               short               
    signed              signed              
    sizeof              sizeof              
    static              static              
                        static_assert       
                        static_cast         
    struct              struct              
    switch              switch              
                        template            
                        this                
                        thread_local        
                        throw               
                        true                
                        try                 
    typedef             typedef             
                        typeid              
                        typename            
    union               union               
    unsigned            unsigned            
                        using               
                        virtual             
    void                void                
    volatile            volatile            
                        wchar_t             
    while               while               

Type of character literal is changed from int to char (§2.14.3)

String literals made const (§2.14.5)

§C1.2 Basic concepts

C++ does not have “tentative definitions” (§3.1).

A struct is a scope in C ++ , not in C (§3.3).

A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage ($3.5).

main cannot be called recursively and cannot have its address taken (§3.6).

C allows “compatible types” in several places, C++ does not (§3.9).

§C1.3 Standard conversions.

Converting void* to a pointer-to-object type requires casting (§4.10).

Only pointers to non-const and non-volatile objects may be implicitly converted to void* (§4.10).

§C1.4 Expressions.

Implicit declaration of functions is not allowed (§5.2.2).

Types must be declared in declarations, not in expressions (§5.3.3, §5.4).

The result of a conditional expression, an assignment expression, or a comma expression may be an lvalue (§5.16, §5.17, §5.18).

§C1.5 Statements.

It is now invalid to jump past a declaration with explicit or implicit initializer (except across the entire block not entered) (§6.4.2, §6.6.4)

It is now invalid to return (explicitly or implicitly) from a function which is declared to return a value without actually returning a value (§6.6.3).

§C1.6 Declarations.

In C++, the static or extern specifiers can only be applied to the names of objects or functions. Using these specifiers with type declarations is illegal in C++ (§7.1.1).

A C++ typedef name must be different from any class type name declared in the same scope (except if the typedef is a synonym of the class name with the same name) (§7.1.3).

const objects must be initialized in C++ but can be left uninitialized in C (§7.1.6).

No implicit int in C++ (§7.1.6).

The keyword auto cannot be used as a storage class specifier (§7.1.6.4).

C++ objects of enumeration type can only be assigned values of the same enumeration type (§7.2).

In C++, the type of an enumerator is its enumeration (§7.2).

§C1.7 Declarators.

In C++, a function declared with an empty parameter list takes no arguments ($8.3.5).

In C++, types may not be defined in return or parameter types (§8.3.5, §5.3.3).

In C++, the syntax for function definition excludes the “old-style” C function (§8.4).

In C++, when initializing an array of characters with a string, the number of characters in the string (including the terminating '\0') must not exceed the number of elements in the array (§8.5.2).

§C1.8 Classes.

In C++, a class declaration introduces the class name into the scope where it is declared and hides any object, function, or other declaration of that name in an enclosing scope (§9.1, §7.1.3).

In C++, the name of a nested class is local to its enclosing class (§9.7).

In C++, a typedef name may not be redeclared in a class definition after being used in that definition (§9.9).

§C1.9 Special member functions.

The implicitly-declared copy constructor and implicitly-declared copy assignment operator cannot make a copy of a volatile lvalue (§12.8).

§C1.10 Preprocessing directives.

Whether __STDC__ is defined and if so, what its value is, are implementation-defined (§16.8).


To ease the regeneration of the comparative keyword table, and to build confidence in the one given, here’s the C++ program used to generate it:

#include <algorithm>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

#define ITEMS_OF( c )   c.begin(), c.end()

enum class Language { c, cpp };

auto compare( Language const a, Language const b )
    -> int
{ return int( a ) - int( b ); }

struct Keyword
{
    string      word;
    Language    language;
    
    friend
    auto operator<( Keyword const& a, Keyword const& b )
        -> bool
    {
        if( int const r = a.word.compare( b.word ) ) { return (r < 0); }
        return (compare( a.language, b.language ) < 0);
    }
};

void add_words_from(
    string const& filename, Language const language, vector< Keyword >& words
    )
{
    ifstream            f( filename );
    string              word;
    
    while( getline( f, word ) )
    {
        words.push_back( Keyword{word, language} );
    }
}

auto main() -> int
{
    vector< Keyword >   words;
    add_words_from( "kwc.txt", Language::c, words );
    add_words_from( "kwcpp.txt", Language::cpp, words );
    sort( ITEMS_OF( words ) );
    
    int const w = 20;

    int previous_column = -1;
    string previous_word = "";
    cout << left;
    for( Keyword const& kw : words )
    {
        int const column = (int) kw.language;
        int const column_advance = column - (previous_column + 1);
        if( column_advance < 0 || previous_word != kw.word )
        {
            cout << endl;
            if( column > 0 ) { cout << setw( w*column ) << ""; }
        }
        else
        {
            cout << setw( w*column_advance ) << "";
        }
        cout << setw( w ) << kw.word;
        previous_column = column; previous_word = kw.word;
    }
    cout << endl;
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
7

In short, C aspires to be a "portable assembler language". It keeps things simple, lets you do things that map almost directly to the underlying hardware, and doesn't present a lot of high level abstractions (you've got functions and.... that's about it)

C++ tries to be everything. A high level language, a low level language, an object oriented language, a multi-paradigm language, a systems programming language, an embedded programming language, and an application development language.

The two language really don't have much in common, other than some shared syntax. A C program might compile as C++ with only minor changes, but it'll have nothing in common with "proper" C++ code written for the language.

jalf
  • 243,077
  • 51
  • 345
  • 550
7

Here's a website showing the "incompatibilities" between c and c++:

http://david.tribble.com/text/cdiffs.htm#C++-vs-C

There are actually quite a few areas where c and c++ diverge (in addition to the classes, template, exceptions, etc).

As far as major differences, here's a list which covers it well:

  • anonymous unions
  • classes
  • constructors and destructors
  • exceptions and try/catch blocks
  • external function linkages (e.g., extern "C")
  • function overloading
  • member functions
  • namespaces
  • new and delete operators and functions
  • operator overloading
  • reference types
  • standard template library (STL)
  • template classes
  • template functions
Evan Teran
  • 87,561
  • 32
  • 179
  • 238
3

Templates is another big difference (in addition to classes/objects). Templates enable for example typesafe generic container types (their first use-case) and (bastardized) lambda-expressions (boost::lambda).

C++ is a much bigger language (not just library) than C.

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
3

This question doesn't have short answer.
In general C++ supports:
- OOP paradigm;
- generic programminng;
- template methaprogramming;
- Abstract data types;
- New libraries and standard supports elemnts of functional paradigm;
- other tools for make your program most supportable;
- Also you could write programs on C-like style but use C++ compiller;


But pure C - a little faster than C++ and more low level.

bayda
  • 13,365
  • 8
  • 39
  • 48
  • C faster? What gives you that idea? Are you saying that if I take a C program, feed it to a C++ compiler, it magically becomes slower? Or perhaps that C++'s std::sort is slower than C's qsort (hint: it isn't). C++ has a lot of tools to increase performance far above C. – jalf Mar 12 '09 at 22:39
  • Of course, it also enables features that, when used, introduces some overhead. But you don't have to use them, and often, using them is no slower than implementing the same yourself in C. It's meaningless to compare the "speed" of two languages. – jalf Mar 12 '09 at 22:39
  • Yes, I agree with "It's meaningless to compare the "speed" of two languages", but I sad "little faster" in general, because in pure-C you cna't use slowly features and you will work only with POD types. – bayda Mar 12 '09 at 22:53
  • C does support generic programming - look at qsort, which allows arbitrary comparison functions. It just sacrifices type safety to do so. – Tom Mar 13 '09 at 04:12
  • C also supports OO programming. Examples from POSIX... A socket is-a file descriptor. A pipe is-a file descriptor. read() and write() are functions that operate on all file descriptors. This is every bit as OO as C++. – Tom Mar 13 '09 at 04:15
  • @Jalf standard C++ didn't have `restrict` until 0x, which C had since 99, so there were plenty of cases where the compiler could not safely apply optimisations to standard C++ code but could apply them to optimise C99 code. – Pete Kirkham Oct 15 '10 at 09:03
  • @Pete: that's a fair point. But I still think it's wrong to say that C is (or was) faster as a whole. That implies that simply taking a program in language X and feeding it to a compiler for language Y, you gain a speedup. C has at least one feature that C++ lacks, which affects performance, but you have to actually use that feature. It's not the language as a whole that's magically faster. Just like C++ has features that at the very least makes it much *easier* to write fast code than their C equivalents. (Expression templates, or just standard library algorithms such as `sort`) – jalf Oct 15 '10 at 11:56
3

Another feature C++ has over C is exception handling in the form of throw ... catch.

Trent
  • 13,249
  • 4
  • 39
  • 36
3

C++ is much more than C with classes. There are many other concepts inside of C++ like templates, function and operator overloading, exceptions and many others already mentioned here. This makes C++ very powerful and flexible, but also hard to learn. It's not that the single concepts are difficult to understand, but the sum of them and how they are playing together. Take a look on boost to see what everything is possible to do with C++. And I guess it tooks ages to understand what happens under the hood, which is very clear in the case of C.

Or to put it in a nutshell: C++ is much more then C with classes, or in other words C++ is much more then Java plus memory management.

quinmars
  • 11,175
  • 8
  • 32
  • 41
2

In 1st of 2 parts of C++ for C programmers, some non-OOP differences are listed:

  • Default arguments to functions
  • Function overloading
  • You can declare local variables wherever in the code you need them, not just at the start of a function (also a C99 feature)
  • References, as in int& x
  • Const-correctness in general
  • Namespaces
  • The built-in boolean type, bool, with true and false keywords (also in C99 via stdbool.h)
  • The inline keyword and associated quirks, including implicit inlining and auto-inlining
  • A much larger standard library than C
Dinah
  • 52,922
  • 30
  • 133
  • 149
  • Refer here too : http://www.preprogrammer.com/all-the-major-difference-between-c-and-c/ –  Jun 22 '16 at 07:49