Home > Article > Backend Development > `char *string` vs. `char* string`: Which Declaration Style is More Logical?
Which Is More Logical: char string vs char string?
In C and C , the declaration of null-terminated strings can be specified in two ways:
Why Use char *string?
The format char *string is generally preferred because it provides clarity in indicating the pointer nature of string. The asterisk (*) directly follows the data type char, implying that string is a pointer to a character, not a character itself.
Why Use char* string?
The format char* string is also used to prevent ambiguity when declaring multiple variables. For instance, consider the following declaration:
char* string1, string2;
In this case, string1 is a character pointer, but string2 is interpreted as a single character because there is no asterisk (*) preceding it. To avoid this confusion, it is better to write:
char *string1, *string2;
This makes it evident that both string1 and string2 are character pointers.
Conclusion
While both notations are technically valid, the convention of using char *string is recommended to ensure clarity and avoid misinterpretations in variable declarations. This practice is particularly beneficial when declaring multiple variables of different types, including pointers and non-pointers.
The above is the detailed content of `char *string` vs. `char* string`: Which Declaration Style is More Logical?. For more information, please follow other related articles on the PHP Chinese website!