Undefined behaviour? Accessing s twice in a statement.

Discussion in 'C Programming' started by Kobu, Mar 5, 2005.

  1. Kobu

    Kobu Guest


    Wonder if the below double access to s is undefined behaviour? Works
    fine, but I know "works" can still be a consequence of undefined

    #include <string.h>

    void mystrcat(char *s, const char *t)
    /* is the below undefined behaviour ? */
    s += strlen(s);

    while(*s++ = *t++)
    ; /* empty statement */

    S is accessed twice (which is a no no), yet the statement "feels" right
    to me.
    Kobu, Mar 5, 2005
    1. Advertisements

  2. :Wonder if the below double access to s is undefined behaviour?

    : s += strlen(s);

    That is well defined. It is equivilent to s = s + strlen(s)
    and you can see that on the right-hand side there are only
    accesses to s without modifications. The restrictions
    are against modifying the same value twice within the same
    sequence point.

    Consider that you would undoubtedly consider this valid:
    y = 3 * x * x + x * 7 + 2;
    (with x being a numeric variable): you don't worry about
    pure accesses on the right hand side.

    Similarily, you know that this is valid:
    i = i + 1;
    (with x being a numeric variable or a pointer): we'd have
    some serious problems with programs if that didn't work.

    So you can access the same variable twice on the RHS and
    you can make an assignment on the LHS to a variable which
    is mentioned on the RHS. Together, we can see that
    s += strlen(s);
    is valid.

    What -would- be a problem is something like:

    y = 3 * x * x++ + x++ * 7 + 2;
    Walter Roberson, Mar 5, 2005
    1. Advertisements

  3. It looks correct to me.

    Chris Williams, Mar 5, 2005
  4. Accessing s twice isn't a problem, if none of those accesses modifies it
    (consider doing "i+i") or of only one of the accesses modifies it and
    all the others are required to determine the new value to be stored
    (as in your code).

    The restrictions on multiple access are when an attempt is made to modify
    an object twice between sequence points (i=i++) or when an object is
    modified and an unrelated access to it is made (which is hard to come
    up with a simple example for; aliasing and multiple side-effects are
    usually involved - consider a[++*i]=a[++*j], if i or j point at the
    element of a[] that gets modified).

    Dave Vandervies, Mar 5, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.