tailieunhanh - C++ Programming for Games Module I phần 8

C++ Programming for Games Module II lập trình game bằng ngôn ngữ C++, chỉ ra các thủ thuật cho bạn, phân tích và viết 1 trò chơi từ đơn giản đến phức tạp | Assume str is a pointer to a null-terminating string. int StringLength char str int cnt 0 Loop through the array until we reach the end. while str cnt 0 cnt Count character. Return the number of characters. return cnt Without the null character telling us when the c-string ends we would not know when to exit the loop and how many characters to count. Using StringLength we can write a function to print out a c-string element-by-element as shown here int main char str 6 H e l l o 0 cout str for int i 0 i StringLength str i cout str i cout endl Again we need to know how many characters are in the c-string in order to know how many times to loop. Incidentally you will never write code to print a c-string like this because cout is overloaded to print a c-string int main char str 6 H e l l o 0 cout str cout str cout endl Note that even cout needs str to be a null-terminating string so that it too can figure out how many characters are in the c-string. You may observe that we could keep track of the number of elements in a c-string in order to do away with StringLength and the null character completely and we would know exactly how many characters are in the c-string. This would work but it is not convenient to have to carry around an extra size variable per c-string. By using a null-terminating c-string the string size can be deduced from the c-string itself which is much more compact and convenient. 190 String Literals Recall that a literal such as is considered to be of type float but what type is a string literal such as hello world C will treat hello world as a const char 12 . The const keyword indicates that the string is a literal and a literal cannot be changed. Because all string literals are specified in the program . they are written in the source code C can know about every literal string the program uses at compile time. Consequently all string literals are allocated in a special global segment of memory when the program starts. The important .