• Re: Code guidelines

    From Vir Campestris@vir.campestris@invalid.invalid to comp.lang.c on Tue Oct 1 11:41:16 2024
    From Newsgroup: comp.lang.c

    On 03/09/2024 17:23, Thiago Adams wrote:
    <snip>
    but...maybe, is better to be a little redundant here?
    I think I prefer to leave "obj->member1->member2 && " even if I know
    it should not be null.

    if (obj->member1 &&
        obj->member1->member2 &&
        obj->member1->member2->member3)
    {

    }

    I think I'd prefer to _omit_ the check that obj->member1->member2 isn't
    null.

    If the code is running correctly that check will never trigger, and is redundant, and will slow things slightly.

    But if the code is not running correctly it will conceal the bug by
    preventing the crash.

    But circumstances may vary. You probably don't want to crash an
    autopilot if at all possible!

    Andy
    --- Synchronet 3.20a-Linux NewsLink 1.114
  • From Kaz Kylheku@643-408-1753@kylheku.com to comp.lang.c on Tue Oct 1 21:39:21 2024
    From Newsgroup: comp.lang.c

    On 2024-10-01, Vir Campestris <vir.campestris@invalid.invalid> wrote:
    On 03/09/2024 17:23, Thiago Adams wrote:
    <snip>
    but...maybe, is better to be a little redundant here?
    I think I prefer to leave "obj->member1->member2 && " even if I know
    it should not be null.

    if (obj->member1 &&
        obj->member1->member2 &&
        obj->member1->member2->member3)
    {

    }

    I think I'd prefer to _omit_ the check that obj->member1->member2 isn't null.

    If the code is running correctly that check will never trigger, and is redundant, and will slow things slightly.

    How about:

    #define vassert(x) (assert(x), 1)

    if (obj->member1 &&
    vassert(obj->member1->member2) &&
    obj->member1->member2->member3)

    If NDEBUG is defined, that just reduces to 1, and is optimized
    away. If NDEBUG is absent, the null pointer crash is replaced
    by an assertion failure.
    --
    TXR Programming Language: http://nongnu.org/txr
    Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal
    Mastodon: @Kazinator@mstdn.ca
    --- Synchronet 3.20a-Linux NewsLink 1.114