Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'thinking in c plus plu (p10)', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | The static char sholds its value between calls of oneChar because its storage is not part of the stack frame of the function but is in the static storage area of the program. When you call oneChar with a char argument s is assigned to that argument and the first character of the array is returned. Each subsequent call to oneChar without an argument produces the default value of zero for charArray which indicates to the function that you are still extracting characters from the previously initialized value of s. The function will continue to produce characters until it reaches the null terminator of the character array at which point it stops incrementing the pointer so it doesn t overrun the end of the array. But what happens if you call oneChar with no arguments and without previously initializing the value of s In the definition for s you could have provided an initializer static char s 0 but if you do not provide an initializer for a static variable of a built-in type the compiler guarantees that variable will be initialized to zero converted to the proper type at program startup. So in oneChar the first time the function is called s is zero. In this case the if s conditional will catch it. The initialization above for s is very simple but initialization for static objects like all other objects can be arbitrary expressions involving constants and previously declared variables and functions. You should be aware that the function above is very vulnerable to multithreading problems whenever you design functions containing static variables you should keep multithreading issues in mind. 430 Thinking in C www. BruceEckel .com static class objects inside functions The rules are the same for static objects of user-defined types including the fact that some initialization is required for the object. However assignment to zero has meaning only for built-in types user-defined types must be initialized with constructor calls. Thus if you don t specify constructor .