Sujet : Re: Code guidelines
De : david.brown (at) *nospam* hesbynett.no (David Brown)
Groupes : comp.lang.cDate : 03. Sep 2024, 14:16:07
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vb726n$3b4rq$1@dont-email.me>
References : 1
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Thunderbird/102.11.0
On 03/09/2024 14:22, Thiago Adams wrote:
Witch style (F1, F2 ..) better represents the guidelines of your code?
//The function f never returns nullptr
int * f();
void F1() {
int* p = f();
if (p == nullptr) {
assert(false);
return;
}
// using *p ...
}
void F2()
{
int* p = f();
assert(p != nullptr);
// using *p ...
}
void F3()
{
int* p = f();
// using *p ...
}
void F4()
{
int* p = f();
if (p) {
// using *p ...
}
}
My preferred style would be :
int * f() __attribute__((returns_nonnull));
Then F3 is appropriate.
(I would also have "(void)" in the declaration, unless I was using C23.)
The same question but for struct members
struct user {
//Name is required, cannot be null.
char * name;
};
void F1(struct user* user) {
if (user->name == nullptr) {
assert(false);
return;
}
// using user->name ...
}
void F2(struct user* user) {
assert(user->name != nullptr);
// using user->name ...
}
void F3(struct user* user) {
// using user->name ...
}
void F4(struct user* user) {
if (user->name) {
// using user->name ...
}
}
void F5(struct user * user) {
if (!user->name) __builtin_unreachable();
// using user->name;
}
I am of the opinion that if something is clearly specified, you make sure it is true when you are responsible for it - and then you can assume it is true when you use the results. It makes no sense to me to do something, and then immediately check that it is done.
Whenever possible, these specifications should be in code, not comments - using whatever tools and extra features you have available for use. Macros and conditional compilation help make code more portable, and can also let you turn compile-time assumptions into run-time checks during debugging.