The C and C++ programming languages are closely related but have many significant differences. C++ began as a fork of an early, pre-standardized C, called "C with Classes", and was designed to be mostly source-and-link compatible with C compilers of the time. Due to this, development tools for the two languages (such as IDEs and compilers) are often integrated into a single product, with the programmer able to specify C or C++ as their source language.
However, C is not a subset of C++, and nontrivial C programs will not compile as C++ code without modification. Likewise, C++ introduces many features that are not available in C and in practice almost all code written in C++ is not conforming C code. This article, however, focuses on differences that cause conforming C code to be ill-formed C++ code, or to be conforming/well-formed in both languages but to behave differently in C and C++.
Bjarne Stroustrup, the creator of C++, has suggested that the incompatibilities between C and C++ should be reduced as much as possible in order to maximize interoperability between the two languages. Others have argued that since C and C++ are two different languages, compatibility between them is useful but not vital; according to this camp, efforts to reduce incompatibility should not hinder attempts to improve each language in isolation. The official rationale for the 1999 C standard (C99) "endorse[d] the principle of maintaining the largest common subset" between C and C++ "while maintaining a distinction between them and allowing them to evolve separately", and stated that the authors were "content to let C++ be the big and ambitious language."
Several additions of C99 are not supported in the current C++ standard or conflicted with C++ features, such as variable-length arrays, native complex number types and the restrict type qualifier. On the other hand, C has gradually worked to reduce some other incompatibilities by incorporating C++ features such as single line comments with // and mixed declarations and code in C99, and adding attributes, type deduction with the auto keyword, and a nullptr constant in C23.
C++ enforces stricter typing rules (no implicit violations of the static type system), and initialization requirements (compile-time enforcement that in-scope variables do not have initialization subverted) than C, and so some valid C code is invalid in C++. A rationale for these is provided in Annex C.1 of the ISO C++ standard.
void * pointer to be assigned to any pointer type without a cast, while C++ does not; this idiom appears often in C code using malloc() memory allocation, or in the passing of context pointers to the POSIX pthreads API, and other frameworks involving callbacks. For example, the following is valid in C but not C++:
void *ptr;
// Implicit conversion from void * to int *
int *i = ptr;
or similarly:
int *j = malloc(5 * sizeof *j);
// Implicit conversion from void * to int *
In order to make the code compile as both C and C++, one must use an explicit cast, as follows (with some caveats in both languages):
void* ptr;
int* i = (int*)ptr;
int* j = (int*)malloc(5 * sizeof *j);
int **
to const int *const * but not the unsafe assignment to const int ** while C allows neither of those (although compilers will usually only emit a warning).const type qualifiers, e.g. strchr returns char * in C, while C++ acts as if there were two overloaded functions (for char * and const char *). In C23 generic selection is used to make C's behaviour more similar to C++'s.enum enumerators) were always of type int in C, whereas they are distinct types in C++ (and C23 or later) and may have a size different from that of int.[needs update]const variable must be initialized; in C this is not necessary.void fn(void) {
goto flack;
int i = 1;
flack:
printf("Reached flack");
}
longjmp() results in undefined behaviour in C++ if the jumped-over stack frames include objects with nontrivial destructors. The C++ implementation is free to define the behaviour such that destructors would be called. However, this would preclude some uses of longjmp() which would otherwise be valid, such as implementation of threads or coroutines switching between separate call stacks with longjmp() — when jumping from the lower to the upper call stack in global address space, destructors would be called for every object in the lower call stack. No such issue exists in C.int n;
int n = 10;
struct, union or enum is valid, but it is invalid in C++, because in C, struct, union, and enum types must be indicated as such whenever the type is referenced whereas in C++, all declarations of such types carry the typedef implicitly.
enum Bool { FALSE, TRUE };
typedef int Bool;
// in C, Bool and enum Bool are distinct
int foo();, specifies that the parameters are unspecified. Therefore, it is legal to call such a function with one or more arguments, e.g. foo(42, "hello world"). In contrast, in C++ a function prototype without arguments means that the function takes no arguments, and calling such a function with arguments is ill-formed. In C, the correct way to declare a function that takes no arguments is by using void, as in int foo(void);, which is also valid in C++; since C23, int foo(); is guaranteed to take no parameters. Empty function prototypes are a deprecated feature in C99 (as they were in C89).struct types, but the scope is interpreted differently: in C++, a nested struct is defined only within the scope/namespace of the outer struct, whereas in C the inner struct is also defined outside the outer struct.struct, union, and enum types to be declared in function prototypes, whereas C++ does not.C99 and C11 added several additional features to C that have not been incorporated into standard C++ as of C++20, such as complex numbers, variable length arrays (complex numbers and variable length arrays are designated as optional extensions in C11), flexible array members, the restrict keyword, array parameter qualifiers, and compound literals.
float complex and double complex primitive data types was added in the C99 standard, via the _Complex keyword and complex convenience macro. In C++, complex arithmetic can be performed using the complex number class, but the two methods are not code-compatible. (The standards since C++11 require binary compatibility, however.)void foo(size_t x, int a[*]); // VLA declaration
void foo(size_t x, int a[x]) {
printf("%zu\n", sizeof a); // same as sizeof(int *)
char s[x * 2];
printf("%zu\n", sizeof s); // will print the value of x * 2
}
#define ADD(A, B) (A + B) used as ADD(4, ) will be expanded into (4 + ).struct X {
int m;
long n;
char bytes[];
};
restrict type qualifier defined in C99 was not included in the C++03 standard, but most mainstream compilers such as the GNU Compiler Collection, Microsoft Visual C++, and Intel C++ Compiler provide similar functionality as an extension.int foo(int a[const]); // equivalent to int *const a
int bar(char s[static 5]); // annotates that s is at least 5 chars long
struct X a = (struct X){4, 6}; // The equivalent in C++ would be X{4, 6}. The C syntactic form used in C99 is supported as an extension in the GCC and Clang C++ compilers.
foo(&(struct X){4, 6}); // The object is allocated in the stack and its address can be passed to a function. This is not supported in C++.
if (memcmp(d, (int[]){8, 6, 7, 5, 3, 0, 9}, n) == 0) {
// ...
}
In C++:
using Digits = int[];
if (std::memcmp(d, Digits{8, 6, 7, 5, 3, 0, 9}, n) == 0) {
// ...
}
char s[20] = { [0] = 'a', [8] = 'g' }; // allowed in C, not in C++
[[noreturn]] attribute in C++ whereas C uses a distinct keyword, _Noreturn. In C23, the attribute syntax is adopted while _Noreturn is deprecated.case 0...9: covers all cases from 0 to 9, inclusive). This feature is proposed for inclusion into C++29._Generic selection for macros to allow for compile-time deciding of expressions, which can be seen as emulating function overloading. C++ has no need for this as C++ supports function overloading and template specialization.typeof operator which produces a type of either a type or an expression. In C++, the equivalent feature is decltype.template, new and class are keywords in C++.
struct template {
int new;
struct template *class;
};
There are a few syntactic constructs that are valid in both C and C++ but produce different results in the two languages.
'a' are of type int in C and of type char in C++, which means that sizeof 'a' will generally give different results in the two languages: in C++, it will be 1, while in C it will be sizeof(int). As another consequence of this type difference, in C, 'a' will always be a signed expression, regardless of whether or not char is a signed or unsigned type, whereas for C++ this is compiler implementation specific.const variables unless they are explicitly declared extern, unlike C in which extern is the default for all file-scoped entities. In practice this does not lead to silent semantic changes between identical C and C++ code but instead will lead to a compile-time or linkage error.inline functions: ordinary external definitions (where extern is explicitly used) and inline definitions. C++, on the other hand, provides only inline definitions for inline functions. In C, an inline definition is similar to an internal (i.e. static) one, in that it can coexist in the same program with one external definition and any number of internal and inline definitions of the same function in other translation units, all of which can differ. This is a separate consideration from the linkage of the function, but not an independent one. C compilers are afforded the discretion to choose between using inline and external definitions of the same function when both are visible. C++, however, requires that if a function with external linkage is declared inline in any translation unit then it must be so declared (and therefore also defined) in every translation unit where it is used, and that all the definitions of that function be identical, following the ODR. Static inline functions behave identically in C and C++.bool with constants true and false, but they are defined differently.
bool is a built-in type and a reserved keyword._Bool, is introduced as a new built-in Boolean type. The header stdbool.h provides macros bool, true and false that are defined as _Bool, 1 and 0, respectively. Therefore, true and false have the type int.bool (and its values true and false) are keywords.char8_t, char16_t and char32_t to encode a single UTF code unit. C23 includes these, but as typedefs to other integer types rather than distinct built-in types, such that their names are not reserved keywords, in <uchar.h>.int is signed or unsigned while in C++ it is always signed to match the underlying type.Several of the other differences from the previous section can also be exploited to create code that compiles in both languages but behaves differently. For example, the following function will return different values in C and C++:
extern int T;
int size(void) {
struct T { long i, j; };
return sizeof(T);
// C: return sizeof(int)
// C++: return sizeof(struct T)
}
This is due to C requiring struct in front of structure tags (and so sizeof(T) refers to the variable), but C++ allowing it to be omitted (and so sizeof(T) refers to the implicit typedef). Beware that the outcome is different when the extern declaration is placed inside the function: then the presence of an identifier with same name in the function scope inhibits the implicit typedef to take effect for C++, and the outcome for C and C++ would be the same. Observe also that the ambiguity in the example above is due to the use of the parenthesis with the sizeof operator. Using sizeof T would expect T to be an expression and not a type, and thus the example would not compile with C++.
While C and C++ maintain a large degree of source compatibility, the object files their respective compilers produce can have important differences that manifest themselves when intermixing C and C++ code. Notably:
For these reasons, for C++ code to call a C function foo(), the C++ code must prototype foo() with extern "C". Likewise, for C code to call a C++ function bar(), the C++ code for bar() must be declared with extern "C".
A common practice for header files to maintain both C and C++ compatibility is to make its declaration be extern "C" for the scope of the header:
In foo.h:
// If this is a C++ compiler, use C linkage
#ifdef __cplusplus
extern "C" {
#endif
// Any symbol declared here gets C linkage
void foo();
int bar(int a, int b);
// If this is a C++ compiler, end C linkage
#ifdef __cplusplus
}
#endif
Differences between C and C++ linkage and calling conventions can also have subtle implications for code that uses function pointers. Some compilers will produce non-working code if a function pointer declared extern "C" points to a C++ function that is not declared extern "C".
For example, the following code:
void qux();
extern "C" void foo(void (*fp)(void));
void bar() {
foo(qux);
}
Using Sun Microsystems' C++ compiler, this may produce the following warning:
"test.cpp", line 5: Warning (Anachronism): Formal argument fp of type
extern "C" void(*)() in call to foo(extern "C" void(*)()) is being passed
void(*)().
This is because qux() is not declared with C linkage and calling conventions, but is being passed to the C function foo().