C ++ keywords and keywords

Source: Internet
Author: User
Tags case statement float double integer numbers switch case

C ++ keywords and keywords

Here is a game: it requires a program that complies with the C ++ standard and contains at least ten consecutive and different keywords. Continuity means that it cannot be separated by identifiers, operators, and punctuation marks. Note the "different" requirements here.

Int main () {return sizeof (int );}

This paper, and this can be any length. It should be possible to come up with an animation. Let's start from long ago,

Unsigned long int ago;
Const volatile unsigned long int ago;
Extern const volatile unsigned long int ago;
Extern inline const volatile unsigned long int f ();
Template extern inline const volatile unsigned long int operator * (const Type &);
Template extern inline const volatile unsigned long int operator and (const Type & lhs, const Type & rhs); // If operators are allowed & converted into keywords and

We emphasize different keywords, so we have to use long int instead of long int.
Typeid can also be cascaded. Unlike sizeof, parentheses must be added. If the parameter is an expression rather than a data type, sizeof does not need to be enclosed by parentheses. New does not have this restriction.

#include <typeinfo>int main(){    const std::type_info& info = typeid(typeid(typeid(typeid(int))));    return 0;}

The C ++ specification also requires that # include <typeinfo> be used when the typeid keyword is used. Otherwise, the drill-formed command is used wherever the typeid keyword is used. New sometimes requires the # include <new> header file.

Sizeof new const volatile signed long int ();

The best answer to limit different keywords is:

Int main () {if (false); else do throw sizeof new const volatile signed long int (); while (false); return 0 ;}Spoiler alert

 

Back to the topic, C ++ was born in 1983 and now has many keywords. Here is a detailed list.


Some operators and punctuation marks of C ++ require characters other than the ISO 646 code set: {,}, [,], #, \, ^, | ,~. To use character sets (such as German DIN 66003) that do not contain these character codes, C ++ defines two alternatives: additional keywords correspond to these operators, A special two-element group or triple consisting of ISO 646 compatible characters is interpreted as a non-ISO 646 character.

Preferred && & = & | ~ ! ! = | | = ^ ^ =
Alternative And And_eq Bit_and Bitor Compl Not Not_eq Or Or_eq Xor Xor_eq

Using a two-element group and a triple may cause some strange problems and affect code reading. The C ++ standard intends to abolish the triple symbol in C ++ 17 ?? <???> ?? (??) ?? = ?? /?? '??! ?? -. The two-element group <: is replaced with a [symbol, so std: vector <: std: string> is incorrectly treated as std: vector [: std :: string> treat. The current keyboard has these symbols, so they do not need to be replaced. After all, symbols are easier to read than strings. If you use add/subtract/multiply/devide to replace the addition, subtraction, multiplication, and Division symbols in mathematical operations, the reading is uncomfortable. This is why operators are overloaded by C ++, matrix operations can be directly written (A + B)/(C * D), instead of divide (add (A, B), multiply (C, D ));

 

Basic Data Type void bool char wchar_t short int long unsigned float double, Boolean value true false, and char16_t char32_t nullptr keyword added in C ++ 11.
Char, signed char, and unsigned char are different types. During GCC compilation, you can use the compilation option-fsigned-char or-funsigned-char to specify the char as signed char or unsigned char respectively. Many programs directly write char, hoping it is signed or unsigned. Programmers like to be short. Like the int keyword, the default signed type is not written. However, sometimes the binary stream is processed and expressed as an integer in the range [0,256.
We can see that there are so many plastic shapes in this table. In fact, I prefer the short uint8_t/int8_t/.../int32_t. You will see that many code projects define their own set of integer data to avoid the problem of porting a 16-bit integer program to a 32-bit system or a 32-bit integer program to a 64-bit system. In addition, C ++ has no requirements for the order of keyword modification, which makes some programmers very tangle.

The gnu stl Library also has long unsigned int in this order.
# Ifndef _ SIZE_TYPE __
# Define _ SIZE_TYPE _ long unsigned int
# Endif

The true/false type is bool. What is the nullptr type?

typedef decltype(nullptr) nullptr_t;

This type definition is awesome, and the New Keyword decltype is also blank. If the two overloaded functions fun can accept different pointer types, such as void fun (int *) and void fun (float *), then compiling fun (NULL) will have a ambiguity error. Another std: nullptr_t void fun (std: nullptr_t nullp) function can be defined. This fun (NULL) Compilation failed, but fun (nullptr) can pass.

Wchar_t represents the encoding in a Unicode Character Set, UTF-16 on Windows, and UTF-32 on Unix-like systems. Sizeof (wchar_t) is implementation defined, with poor portability. Generally, it is two bytes in Windows and four bytes in Unix-like systems. Windows accepts wide characters and makes them standard. We can see that many Windows APIs have two versions, functionNameA and functionNameW, which correspond to the ANSI and wide character versions respectively. This blog lists possible mistakes made by using wchar_t.

The C specification does not specify the specific type of wchar_t, which is related to the compiler implementation. It may be 8/16/32 bits, signed or unsigned. The key lies in the selected Encoding Character set. Pay attention to the differences between Character sets (Charset) and Character Encoding (Character Encoding). ASCII/GBK/BIG5/GB18030 is the Character set and Unicode is the Character set. At that time, various countries had their own coding solutions. There were GBK, GB18030, and BIG5 in China. This was no problem in China, but the network spread all over the world, and people outside the country had garbled characters. Unicode came into being. The Unicode Character Set has several encodings: UTF-7/UTF-8/UTF-16.
Unicode characters are recommended. wchar_t is not recommended. Instead, char16_t/char32_t of fixed length is used.

ISO/IEC 10646: 2003 Unicode Standard 4.0:
"The width of wchar_t is compiler-specific and can be as small as 8 bits. consequently, programs that need to be portable should SS any C or C ++ compiler shocould not use wchar_t for storing Unicode text. the wchar_t type is intended for storing compiler-defined wide characters, which may be Unicode characters in some compilers."

 

 

The C-language keyword int is the most commonly used. I often think that the modification of short/long makes int appear redundant. Short int has the same semantics as short, and long int has the same semantics as int. Long and short are relative, so the long int type is displayed. Long was proposed in 1995, and C ++ refused to join because C was not added. Many compilers have implemented them by themselves. 10 years later, we thought it was necessary to standardize them. (Maybe in the future, the integer calculation range needs to be expanded to 128 bits, so we need to call a long int? Good syntax) I personally think that when the programming language was born, we should try to make the keyword semantic orthogonal, although the standard sets sizeof (short) <= sizeof (int) <= sizeof (long), but many compilers still treat int as long int. The C language can be transplanted. Java is very clever and specifies the length of each language. The short/int/long values are 2/4/8 bytes.
There is a header file <stdint. h> which specifically defines various integer numbers, such as int8_t, int16_t, int32_t, and int64_t, as well as the unsigned type. In fact, short/long/signed are both adjectives, and int is a noun. Therefore, it is right to declare an integer that does not end with int. Instead of writing long int, it is better to write long or even int64_t. I also thought that if sizeof (int) = sizeof (long int), on a 32-bit machine, either long is redundant or int is redundant. Then I thought of the long double type. I think int is unnecessary.

To select keywords, perform syntactic orthogonal as much as possible, and express all meanings as much as possible. A small part can be reserved for extension. From the changes in C ++ 11, we can see that as far as possible, no new keywords are added. The double brackets extend [[] and the right value symbol &&; add new keywords such as alignas/alignof/thread_local. To recycle almost unnecessary keywords, auto is shining again, and the template can do the same thing. auto can now be simply done.
When adding a new keyword, you need to consider that it is rarely used in the History code. The appearance of some context-related (contex-sensitive) KEYWORDS final and override. They are not keywords, but they can be found by the compiler at the end of the function. You can imagine how many historical codes need to be modified if you select keywords for common words such as final override. Apparently, final and override are learned from the Java language. Python has been upgraded from 2.x to 3.x, which is incompatible with the language, although there are documents and tools to help migrate code.
Because final and override are context-related, you can write and compile them as well.

class Base{public:    virtual int override(int )    {        std::cout<<"please override me"<<std::endl;        return 0;    }};class Fun: public Base{public:    virtual int override(int ) override final    {        int override = 42;        return override;    }};int main(){    int me = 0x3e;    Fun hey;    hey.override(me);    return 0;}

 

Before C ++ 11, the C ++ standard handed in many things for the compiler to handle themselves, such as whether to generate constructors, memory alignment, RVO optimization, and enum types, now, you can explicitly ask for a different set. The type of enum is implementation defined. Many compilers use the smallest integer range. Therefore, you will see many such statements in many Microsoft code:

typedef enum D3DTEXTUREADDRESS {     D3DTADDRESS_WRAP         = 1,    D3DTADDRESS_MIRROR       = 2,    D3DTADDRESS_CLAMP        = 3,    D3DTADDRESS_BORDER       = 4,    D3DTADDRESS_MIRRORONCE   = 5,    D3DTADDRESS_FORCE_DWORD  = 0x7fffffff} D3DTEXTUREADDRESS, *LPD3DTEXTUREADDRESS;

The last enum constant is XXX_FORCE_DWORD = 0x7fffffff, and the length of sizeof (D3DTEXTUREADDRESS) is fixed to 4.

Alignment is the detail that the language designer wants to cover up. However, when the C ++ 11 programming method becomes more complex, it is often necessary to provide users with more underlying means. In some cases, although the user cannot guarantee that the writing of the platform is irrelevant, or the platform is used to the best code, however, you only need to modify the alignas parameter to ensure the portability and performance of the program. It is also a good choice. C ++ 11 supports alignment from syntax rules to libraries. It can be said that the alignment mode is quite complete.

template <typename T>class alignas(sizeof(T)<<2) Color{    T r, g, b, a;};

 

Add features to keywords. In the past, default and delete have only one purpose: default is the default branch in the switch statement, and delete is the release of memory. Now there is one more use: = delete indicates that the function is deleted, and = default indicates that the function is generated by default during the compilation period. In the past, using could only be used with namespace, but now all the work done by typedef can be taken over, which is more intuitive and easy to understand. I used to write typedef long int int64; now you can write using int64 = long int; how is it? You can also use the equal sign "assign value" for the data type.
After C ++ 11 came out, you don't have to look at the compiler's face. No constructor needs to be defined here, so that the compiler can generate the constructor itself; the constructor needs to be defined here; otherwise, the compiler will do shallow copying. Now you can show how the compiler works.

class noncopyable{private:    noncopyable(const noncopyable& );            // not defined    noncopyable& operator=(const noncopyable&);  // not defined};

Previously, we didn't want to assign values between objects. The assignment constructor and operator = are limited to private and are not defined. Now we have a better way of writing:

class noncopyable{public:    noncopyable(const noncopyable& ) = delete;    noncopyable& operator=(const noncopyable&) = delete;};

Private can be declared to prevent calls. Deliberately failing to implement these functions means that if you want to access them externally through the member functions or the friend class, although the compilation can be successful, an error will be reported during the link due to undefined symbols. In C ++ 11, the situation is different. = Delete indicates that this method will not be generated during the compilation period. Therefore, this method can be killed during the compilation period without being postponed to the link. Although the access permission here is not important to C ++ 11, in general, it is best to declare public rather than private for the function marking the delete operation. Some compilers only report an access permission error (the error is as follows) when checking the call of member functions ). Obviously, delete is the focus here, or the priority of errors is higher. Of course, not only member functions can be deleted, but non-member functions and functions instantiated by templates can also be deleted. Compared with C ++ 98, this is an improvement.

Error: 'pea: Log (const pea: Log &) 'is private
Log (const Log & log) = delete;

 

Please note that the using namespace std should not be written in the. h file, but also in the. cpp file. The header file may be included by other header files, and the namespace is contaminated, but the. cpp file does not. Unless you intentionally want to # include "XXX. cpp. Add the method void onKeyReleased (EventKeyboard: KeyCode keyCode, Event * event) in class HelloWorld in the cocos2d-x; will compile but, the error is as follows:

1> classes \ HelloWorldScene. h (17): error C2653: 'eventkeyboard': is not a class or namespace name (.. \ Classes \ AppDelegate. cpp)
1> classes \ HelloWorldScene. h (17): error C2061: syntax error: identifier 'keycode' (.. \ Classes \ AppDelegate. cpp)
1> classes \ HelloWorldScene. h (17): error C2653: 'eventkeyboard': is not a class or namespace name (.. \ Classes \ HelloWorldScene. cpp)
1> classes \ HelloWorldScene. h (17): error C2061: syntax error: identifier 'keycode' (.. \ Classes \ HelloWorldScene. cpp)
1> classes \ HelloWorldScene. cpp (72): error C2276: '&': illegal operation on bound member function expression

In fact, the modification is very simple. Just add the namespace where EventKeyboard and KeyCode are located.

Void onKeyReleased (cocos2d: EventKeyboard: KeyCode keyCode, cocos2d: Event * event );

However, you do not need to add it in HelloWorldScene. cpp, because USING_NS_CC; that is, using namespace cocos2d; introduces all cocos2d.

void HelloWorld::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event){  //TODO}

 

The virtual keyword is used to declare a virtual function. Adding = 0 at the end of the virtual function indicates a pure virtual function. When the function name and parameter may change dynamically, You need to manually check whether the base class is consistent with the function of the derived class, and whether the member function of the derived class overwrites the member function of the base class. This boring work should be done by the compiler. Therefore, C ++ 11 introduces the context-related keyword override. If it is not overwritten, the compiler will report an error.

In C ++ 98, a null pointer is represented by a literal value of 0. After C ++ 11 is standard, it is best to use nullptr, so someone will ask if the declaration of the pure virtual function = 0 should be corrected to = nullptr, and it won't work if you try it. The syntax must be 0, not the expression (42-42), or even 0L, 0u 0x0 (the clang compiler previously supported this writing method. Some people choose to use macro # define pure = 0, which seems to be easy to identify virtual functions from the declaration. This writing is not very good. Bjarne Stroustrup, father of C ++, explains that the abstract/pure keyword is not added. (Keywords abstract in Java)

Bjarne Stroustrup in his bookThe Design & Evolution of C ++, Section 13.2.3

The curious = 0 syntax was chosen over the obvious alternative of introducing a new keyword pure or abstract because at the time I saw no chance of getting a new keyword accepted. had I suggested pure, Release 2.0 wocould have shipped without abstract classes. given a choice between a nicer syntax and abstract classes, I chose abstract classes. rather than risking delay and incurring the certain fights over pure, I used the tradition C and C ++ convention of using 0 to represent "not there. "The = 0 syntax fits with my view that a function body is the initializer for a function also with the (simplistic, but usually adequate) view of the set of virtual functions being implemented as a vector of function pointers.

= 0 seems confusing. I think that a pure virtual function is an unimplemented function and that it is a null (nullptr) function pointer. In fact, pure virtual functions can also be implemented. It cannot be implemented during declaration, but must be defined externally. C ++ 11 introduces the context-related keyword concept. Now, it is more intuitive to introduce pure as the context-related keyword and replace = 0 with pure.

class Base{public:    virtual void fun() = 0;};void Base::fun(){    std::cout<<"pure virtual implementation\n";}class Derived: public Base{public:    virtual void fun() { Base::fun(); }};

There are two other topics: destructor can be pure virtual functions, but must be defined; otherwise, a link error may occur, because the inherited class calls the destructor of the base class during the destructor, the symbol cannot be found. Pure virtual functions require non-Abstract subclass implementation. Therefore, it is best to grant the protected permission to the constructors of the base class.




Operator "" added in C ++ 11, user-defined semantics (user literal)RestrictionsIn the following types,

(Const char *)
(Unsigned long int)
(Long double)
(Char)
(Wchar_t)
(Char16_t)
(Char32_t)
(Const char *, std: size_t)
(Const wchar_t *, std: size_t)
(Const char16_t *, std: size_t)
(Const char32_t *, std: size_t)

No. For example, the floating point type is only long double, but not float or double. Why? Suppose we have a function syntax for angle and radian conversion.

constexpr long double operator"" _deg ( long double deg ){    return deg*M_PI/180;}

When we want to express M_PI radian, we can write it as 180_deg. Note that 180 and _ deg are a whole and there cannot be spaces between them. (Just like the suffix long int degree = 180L; float pi = 3.14159265f in C/C ++ ). To distinguish float, double, and long double data types, our definition should be as follows:

Float radian1 = 180f_deg;
Double radian2 = 180_deg;
Long double radian3 = 180L_deg;
Obviously, the compiler will parse valid characters without spaces as a word (token), so f_deg becomes a word. As mentioned above, there cannot be spaces between f and _ deg, therefore, we cannot meet the needs of different floating point types, including integer types. To avoid truncation or narrowing, the type of the maximum range is adopted. The integer type is unsigned long int, and the floating point type is long double. The integer is long int rather than unsigned long int because the addition and subtraction of the signed and unsigned numbers will be extended to the unsigned type. Here it seems that unsigned long int Is the Largest Integer Range, so there should be no 128-bit integer.

 

Try to push the computation to the compiler instead of the runtime. In C ++ 11, a New Keyword static_cast and constexpr is added. The boost library can simulate static_cast.
Previously, we used a macro to define FOURCC.

#define MAKE_FOURCC(ch0, ch1, ch2, ch3) \    ((uint32_t)(uint8_t)(ch0) |         \    ((uint32_t)(uint8_t)(ch1) << 8) |   \    ((uint32_t)(uint8_t)(ch2) << 16) |  \    ((uint32_t)(uint8_t)(ch3) << 24))   \

Now we can directly use the constexpr function to write, instead of Type insecure macros. Because the value is calculated by the compiler, the calculated integer value can be directly used in the switch case statement without errors.

constexpr uint32_t makeFourCC(uint8_t ch0, uint8_t ch1, uint8_t ch2, uint8_t ch3){    return static_cast<uint32_t>(ch0 | (ch1<<8) | (ch2<<16) | (ch3<<24));}constexpr uint32_t RIFF = makeFourCC('R', 'I', 'F', 'F');constexpr uint32_t WAVE = makeFourCC('W', 'A', 'V', 'E');constexpr uint32_t FMT_ = makeFourCC('F', 'M', 'T', ' ');constexpr uint32_t DATA = makeFourCC('D', 'A', 'T', 'A');

 


C ++ has not moved around for more than a decade, creating a boost library. I also learned a lot from languages that were later developed by myself. For example, when defining Java class members, the default value is given, the delegate constructor, and the Native String constant of Python, this makes it easy for programmers to learn and use C ++ strings.

 

..

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.