开发者

Naming convention for allocated/non-allocated strings

开发者 https://www.devze.com 2023-03-16 03:05 出处:网络
Are there any common naming conventions to differentiate between strings that are allocated and not allocated? What I am l开发者_StackOverflow中文版ooking for is hopefully something similar to us/s fr

Are there any common naming conventions to differentiate between strings that are allocated and not allocated? What I am l开发者_StackOverflow中文版ooking for is hopefully something similar to us/s from Making Wrong Code Look Wrong, but I'd rather use something common than make up my own.


The us / s convention in the article is somewhat useful, but it misses a greater point. The point is that variable naming conventions are only as good at protecting from missteps as documentation.

For example:

#Version 1

char* sHello = "Hello";
printf("%s\n", sHello);

which gets modified eventually to

#Version 2
char* sHello = "Hello";
... 100 lines of code ...
sHello = realloc(sHello, strlen(sHello)+7);
strcpy(sHello+strlen(sHello), " World");
... 100 lines of code ...
printf("%s\n", sHello);

When you really want to make a coding convention work, you can't rely on some sort of arbitrary (and yes, they are all arbitrary) naming conventions. You have to back up that naming convention with a means of failing the build. In the above case, judicious use of the keyword const would have done the trick, but the coding convention will lull people into complacency that it's right because it's named a certain way.

It's the documentation problem all over again, eventually in-code documentation gets out-of-sync with the code, and your in-code naming convention will eventually get out-of-sync with the usage of those names.

Now, if you want to add typing information to C (which is really what you're getting at), do it via a system that actually adds types to c, typedef. Then put in place a system that can verify if the type is not being used when it is required and fail the build. Anything else will cost you too much after-the-fact searching / maintenance / cleanup, and half of an implemented coding style is just so much worse than even a bad coding style.

0

精彩评论

暂无评论...
验证码 换一张
取 消