Love the Thinking in series, so I played this name. The idea of this article also comes to this book, or refers to comparison, or in-depth mining, or makes picking out, or has a feeling, including Thinking In C , and even including Thinking in Java.
Thinking Again In C (5) In-depth understanding of the initialization
Keywords: C , Initialization, Object, Object
A piece of code from the actual project, simplified form as follows: Switch (t) {case 0: int A = 0; brefault: Break;} Is there any problem? It doesn't seem. Please use the compiler to compile ... Well? ! An error "error C2361: Initialization of 'a' is Skipped by 'Default' Label". how can that be? Several thinking, understanding: C convention If the program jumps from Switch to the Default, it will cause the object A until it is not initialized. Ensure that the initialization of the object is an important design philosophy of C , so the compiler will strictly check this violation, and the default statement is not used in the sample code described above, but it is not intended to use it in consideration of the change in code. So being blocked. It is easy to solve the cause and solve it. As long as you clearly limit the domain of the object A. Switch (t) {case 0: {// added for fix problem int a = 0; Break;} // added for fix, if you really need to use object a throughout the Switch statement, then INT A = 0; before moving to the switch statement. However, from the original statement, it doesn't seem like this, so I recommend the previous solution.
has it ended? No. Let us continue to see the exact meaning of "Initialization" in the error message information (that is, the initialization). C is very important, so it will often give us a illusion, seemed that the object will definitely pass through the initialization process. What is the real situation? Still use instances to prove it. Switch (t) {case 0: int A; a = 0; Break; default: Break;} compiled, this time no error. Obvious Int a; defined objects, but did not initialize, otherwise the original error should be reported. Take a look at the user's custom type. Class B {};
Switch (t) {casse 0: B; Break; default: Break; If you add a constructor to classes, the situation is different. Class B {public: // added for initialization b () {} // added for initialization}; this will reproduce the original error. It is proved that there is a constructor, and the compiler will perform initialization and safety check.