Get the App
SLTechnology News&Howtos  ›  Development  › 

What details has C++ improved on the basis of C

Shulou Source: shulou.com Published: 2022-06-02 09:21:15 09月17日 Update

This article mainly introduces "what details did C++ improve on the basis of C". In daily operation, I believe many people have doubts about what details C++ improved on the basis of C. the editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "what details C++ has improved on the basis of C". Next, please follow the editor to study!

Variable definition location

ANSI C stipulates that all local variables must be defined at the beginning of the function, and there can be no other execution statements until the variables are defined. The C99 standard removes this restriction, but VC/VS 's support for C99 is not active and still requires variables to be defined at the beginning of the function. Take a look at the following code:

# include int main () {int a * scanf ("% d", & a); int b * scanf ("% d", & b); int c = a + b * printf ("% d\ n", c); return 0;}

Save the code to the source file main.c, then it can be compiled under GCC and Xcode, but an error will be reported under VC/VS. GCC and Xcode support C99 very well, and you can define variables anywhere in the function; but VC/VS has little support for C99, and all variables must be defined at the beginning of the function.

Save the above code to the source file main.cpp, and it can be compiled under GCC, Xcode, and VC/VS. This is because C++ removes the original restriction that variables are defined before they are used, and it is not mandatory to define all variables at the beginning of the function.

Note the suffix of the source file, .c is the C language code, and .cpp is the C++ code, which are compiled differently.

Another benefit of unrestricting is that variables can be defined in the control statement of the for loop, as shown in the following example:

# include using namespace std;int sum (int n) {int total = 0 role / define the variable ifor (int item1; I) inside the conditional statement of the for loop

Tags: Variables clocking code results loops functions support fundamentals details beginnings types statements facets learning restrictions Boolean source files languages see operations Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Information NVidia Shulou Technology Redmi