The difference and connection between C language and C++, most people are wrong

foreword

What is the relationship between C language and C++?

First of all, C++ and C language are originally two different programming languages, but C++ is indeed an extension and extension of C language, and it provides backward compatibility for C language. There is nothing wrong with some people saying that C++ completely contains the C language.

When C++ was first invented by Bjarne Stroustrup, it was originally called "C with Classes", which means "C with classes".

Obviously, it expands object-oriented features and mechanisms such as classes on the basis of C language. But after a step-by-step revision and many evolutions, it finally formed the huge programming language that supports a series of major features.

1. C language is a process-oriented language, while C++ is an object-oriented language

We all know that C language is a process-oriented language, and C++ is an object-oriented language. The difference between C and C++ is to compare the difference between process-oriented and object-oriented.

(1) The difference between process-oriented and object-oriented

Process-oriented: Process-oriented programming is to analyze the steps to solve the problem, and then implement these steps step by step, and call them one by one when using them.

Object-oriented: Object-oriented programming is to decompose the problem into various objects. The purpose of establishing an object is not to complete a step, but to describe the behavior of something in the entire problem-solving step.

(2) Advantages and disadvantages of process-oriented and object-oriented

process-oriented language

Advantages: The performance is higher than that of object-oriented, because the class needs to be instantiated when calling, the overhead is relatively large, and it consumes resources; such as single-chip microcomputer, embedded development, Linux/Unix, etc. generally adopt process-oriented development, and performance is the most important factor.

Disadvantages: no object-oriented, easy to maintain, easy to reuse, easy to expand

object-oriented language

Advantages: easy to maintain, easy to reuse, and easy to expand. Due to the characteristics of object-oriented encapsulation, inheritance, and polymorphism, a low-coupling system can be designed to make the system more flexible and easier to maintain

Disadvantages: Performance is lower than process-oriented.

2. Specific language differences

1. Different keywords

C language has 32 keywords;

C++ has 63 keywords;

2. Different suffix names

C source files have a suffix of .c, and C++ source files have a suffix of .cpp. In VS, if nothing is given when creating a source file, the default is .cpp.

3. Return value

In C language, if a function does not specify a return value type, it returns an int type by default; in C++, if a function does not return a value, it must be specified as void.

4. Parameter list

In C language, when a function does not specify a parameter list, it can receive any number of parameters by default; but in C++, because of strict parameter type detection, a function without a parameter list defaults to void and does not receive any parameters.

5. Default parameters

The default parameter is to specify a default value for the parameter of the function when declaring or defining the function. When calling the function, if no actual parameter is specified, the default value is used, otherwise the specified parameter is used. (C language does not support default parameters)

· Semi-default parameters

· All default parameters

Notice:

· In the case of semi-default, the parameters with default values ​​must be placed at the end of the parameter list.

· The default parameter cannot appear in the function declaration and function definition at the same time, and only one of them can be selected.

· The default value must be a constant or a global variable.

· Default parameters must be passed by value or constant.

6. Function overloading

Function overloading: Function overloading is a special case of functions. It refers to declaring several functions with the same name with similar functions in the same scope. The formal parameter lists (number, type, and order) of these functions with the same name must be different. The return value types can be the same or different, which is often used to deal with the problem of implementing similar functions with different data types. (C language does not have function overloading, and C++ supports function overloading).

The rule for generating function symbols in C language is based on the name, which means that there is no concept of function overloading in C language. However, C++ generates function symbols considering the function name, number of parameters, and parameter types. It should be noted that the return value of the function cannot be used as the basis for function overloading, that is to say, the two functions int sum and double sum cannot constitute overloading!

Our function overloading is also a kind of polymorphism, which is called static polymorphism.

Static polymorphism: function overloading, function templates

Dynamic polymorphism (polymorphism at runtime): Polymorphism (virtual functions) in inheritance.

When using overloading, you need to pay attention to scope issues: please see the following code.

I have defined two functions in the global scope. They can be overloaded due to different parameter types. At this time, the calls in the main function can correctly call their respective functions.

But look at the commented-out line of code in the main function. If you put it out, you will be warned: converting a double type to an int type may lose data.

This means that our compiler calls compare of parameter type int for the following two calls. It can be seen that when the compiler calls a function, it first searches in the local scope, and if the search is successful, all calls are made according to the standard of the function. If it is not found, it will be searched in the global scope.

Summary: There is no function overloading in C language. C++ judges overloading based on the number of parameters of the function name and parameter type. It belongs to static polymorphism and must be called overloading under the same scope.

7、const

Variables modified by const in C language are not constants, called constant variables or read-only variables. This constant variable cannot be used as an array subscript. However, variables modified by const in C++ can be used as array subscripts and become real constants. This is the extension of C++ to const.

const in C language: After being modified, it cannot be used as an lvalue, and it can not be initialized, but there is no chance to reinitialize afterwards. It cannot be used as the subscript of the array, but can be modified through the pointer.

Simply put, the difference between it and ordinary variables is that it cannot be an lvalue, and it is the same in other places.

const in C++: real constants. It must be initialized when it is defined, and can be used as the subscript of the array. The compilation rule of const in C++ is replacement (much like a macro), so it is regarded as a real constant. It can also be modified by pointer. It should be noted that C++ pointers may degenerate into C language pointers. For example:

At this time, a is just an ordinary C language const constant variable, and it can no longer be used as an array subscript. (references a value that is not determined at compile time)

When const generates symbols, it is a local symbol. That is, it is only visible in this document. If you have to use it in other files, declare in the file header: externcosnt int data = 10; the generated symbol is a global symbol.

Summary: const in C is called a read-only variable, but it cannot be an lvalue variable; const in C++ is a real constant, but it may degenerate into a constant in C language, and local symbols are generated by default.

8. Quote

When it comes to references, our first reaction is to think of his brother: pointers.

A reference is the same thing as a pointer at the bottom, but its characteristics are completely different from pointers in the compiler.

First define a variable a = 10, then we define a reference b and a pointer p pointing to a respectively. Let's go to the disassembly to see the underlying implementation:

It can be seen that the underlying implementation is completely consistent, take the address of a and put it into the eax register, and then store the value in eax into the memory that references b/pointer p. So far we can say that (under the hood) a reference is essentially a pointer.

Knowing the underlying implementation, let's go back to the compiler. We see that the modification of the value of a, the method of pointer p is *p = 20; that is, the value is replaced after dereferencing.

Let's look at the reference modification again:

We see that the method of modifying the value of a is the same, and it is also dereferencing. It's just that we are different when we call: *p dereference is required when calling p, and b can be used directly. From this we deduce that the reference is a pointer dereference when used directly. p used directly is its own address.

In this way, we also understand that the memory we opened up for the reference cannot be accessed at all. If it is used directly, it is dereferenced directly. Even if &b is printed, the output is the address of a.

Here is a little trick for converting pointers to references: int *p = &a, we move the reference symbol to the left and replace *: int &p = a.

Next, let's see how to create a reference to an array:

intarray[10] = {0};//定义一个数组

We know that if the array is taken out and used, it is the address of the first element of the array array. That is, the int * type.

So what does &array mean? Is the int ** type used to point to an address of the address of array[0]? Don't take it for granted, &array is the entire array type.

Then to define an array reference, according to the above tips, first write the array pointer:

int(*q) [10] = &array;

Overwrite the & on the right with the * on the left:

int(&q)[10] = array;

Test sizeof(q) = 10. We successfully created the array reference.

After the above detailed explanation, we know that the reference is actually taking the address. Then we all know that an immediate value has no address, that is

int&b = 10;

Such code cannot be compiled. Then if you just insist on referencing an immediate value, there is actually no way:

constint &b = 10;

Just modify this immediate number with const, and that's it. why?

At this time, because the modified const will generate a temporary quantity to save this data, naturally there is an address.

9、malloc,free && new,delete

This question is very interesting, and it is also a question that needs to be paid attention to. malloc() and free() are functions in the standard library that dynamically apply for memory and release memory in C language. And new and delete are C++ operators and keywords. The bottom layer of new and delete actually calls malloc and free. They differ in the following ways:

1), malloc and free are functions, new and delete are operators.

2), malloc needs the size before allocating memory, new does not.

For example:

int *p1 = (int *)malloc(sizeof(int));int *p2 = new int; //int *p3 = new int(10);

When malloc needs to specify the size, it also needs type conversion. There is no need to specify the size when new because it can be judged from the given type, and the initial value can also be assigned at the same time.

3) Malloc is not safe and requires manual type conversion, while new does not require type conversion.

4), free only releases the space, delete calls the destructor first and then releases the space (if necessary).

Corresponding to item 5, if a complex type is used, first destruct and then call operator delete to reclaim the memory.

5), new is to call the constructor first and then apply for space (if necessary).

Corresponding to item ④, when we call new (for example, int *p2 = new int; this code), the implementation of the underlying code is: first push 4 bytes (size of int type), and then call operator new function allocation out of memory. Since our code does not involve complex types (such as class types), there is no constructor call. The following is the source code of operator new, which is also an important function implemented by new:

We can see that first malloc(size) applies for the memory of the byte size of the parameter, and if it fails (malloc fails and returns 0), it enters the judgment: if _callnewh(size) also fails, a bad_alloc exception is thrown. The function _callnewh() is to check whether the new handler is available. If it is available, it will release part of the memory and then return to malloc to continue the application. If the new handler is not available, an exception will be thrown.

6) The processing method is different when the memory is insufficient (development failure).

If malloc fails, it returns 0, and if new fails, a bad_alloc exception is thrown.

7), new and malloc open up memory locations are different.

malloc is allocated in the heap area, and new is allocated in the free storage area.

8), new can call malloc(), but malloc cannot call new.

new is implemented with malloc(), and new is unique to C++, and of course malloc cannot be called.

10. Scope

There are only two scopes in C language: local and global. In C++, there are three types: local scope, class scope, and namespace scope.

The so-called namespace is namespace, and we define a namespace to define a new scope. Access needs to be accessed as follows (take std as an example)

std::cin<<"123" <<std::endl;

For example, we have a namespace called Myname, which has a variable called data. If we want to use data in other places, we need to declare in the file header: using Myname::data; so that data uses the value in Myname. But wouldn't we be exhausted if we have to declare every symbol?

As long as we use namespace Myname; we can import all the symbols in it.

This is what we often see using namespace std; means.

Can I learn C++ directly without learning C language?

As mentioned earlier, the first important component of the C++ programming language is "procedure-oriented programming", and this is the domain of the big brother of the C language. Even if you haven't learned C language, you should be able to escape the "process-oriented" part for those who learn C++ directly.

Theoretically speaking, it is not necessary to learn C language before learning C++, but it is often more advantageous to learn C++ after learning C++. At least the part of "process-oriented programming" can be familiar with the road.


Get more resources and pay attention to the official account: Qi Niu Programming C language\C++ learning exchange penguin group: 763855696

Guess you like

Origin blog.csdn.net/weixin_55751709/article/details/129207462