Comparing C and C++ coding practice in different aspects.
Despite both belonging to C family, C and C++ have some difference regarding coding practice. It would save programmer a lot of time if only the difference are addressed, so that they don’t need to consult the voluminous C manual.
This guide is not intended for C beginners. Readers are assumed to have adequate knowledge and practice on basic C/C++ syntax. This guide is more like a lightweight memo addressing the difference in coding practice for those immigrants who are switching from C++ to C.
Error handling
C++ introduces exception and handling feature.
int foo() {
int divident = 1;
int divisor = 0;
int result = divident / divisor;
return result;
}
int main() {
try {
foo();
} catch (Exception e) {
// do some exception handling job.
}
return 0;
}
In C there are no exception throwing and catching grammar, instead programmers use if
statement to catch existence of errors and do something with it, possibly logging error message to stderr
.
int foo() {
int divident = 1;
int divisor = 0;
if (result = divident / divisor) {
fprintf(stderr, "Division by zero is undefined.");
//do something to handle the error.
exit(EXIT_FAILURE);
}
}
Notice that
EXIT_FAILURE
is a constant defined instdlib
library.
File IO
Main() function
Print statement
Abstract Data Type
Nowadays it’s important for a general-purpose language to provide primitives and specialized constructs that support ADT (Abstract Data Type). At the time when C was first created and entered industry, the paradigm of object-oriented design was not yet pushed into public field. So C doesn’t have built-in support for abstract data type. However, people find some systematic way to simulate ADT on top of existing C language primitives.
typedef struct stackCDT* stackADT;
typedef int elementT
struct stackCDT { elementT data[100]; }
void Push(stackADT s, elementT elm);
elementT Pop(stackADT s);
int IsEmptyStack(stackADT s);
C++ has built-in class feature, that makes object-oriented design officially supported and streamlined.
class stack {
public:
stack();
~stack();
void push(elementT elm);
elementT pop();
isEmptyStack();
private:
elementT data[100];
};
Primitive types
C++ has bool
and string
types added on top of C type set.
Boolean type
In C, programmers use int
to simulate bool
type, usually with 0
denoting false
, and 1
, or possibly any value other than 0
, to denote true
.
int IsPositiveNumber() { return a > 0; }
int main() {
int a = 12;
if (IsPositiveNumber(a)) printf("%d is a positive number.n", a);
}
String type
In C, there are strings, but they are not actual primitive type that resembles other types like int
, float
, or double
. In fact, C strings are implemented as character array. More specifically, every string literals in C or C++ is an array storing characters, terminating with the last element
近期评论