Cud any1 let me know how this code works with respect to pecedence and associativity

Thanks in advance

#include <stdio.h>
main()
{
  int i = -3, j = 2, k = 0, m;
  m = ++i && ++j || ++k;
  printf ("\n %d %d %d %d", i,j,k,m);
}

The result for the given code snippet is i = -2, j = 3, k = 0, m = 1

Cud u please explain how u get this result?

The result for the given code snippet is i = -2, j = 3, k = 0, m = 1

Cud u please explain how u get this result?

i is incremented, j is incremented, and both are not 0 (true), so k is not incremented. You're mixing two things that confuse beginners greatly (short circuiting and prefix/postfix side effects). It'd probably be better to break it down a little more until you're more comfortable.

Edited 6 Years Ago by Narue: n/a

you can look at it like this.

m = 0;
i++;
j++;

if (i != 0 && j != 0)
{
    ++k;

    if (k != 0)
        m == 1;
}

but that is a contrived example. Apparently some wikipedia nabob trying to show how clever they are by making a convoluted expression.

i can't see how it has any real learning value. no one will understand the example until after they already understand precedence, and using it to explain precedence will only serve to confuse the beginner.

you can look at it like this.

m = 0;
i++;
j++;

if (i != 0 && j != 0)
{
    ++k;

    if (k != 0)
        m == 1;
}

Not quite. k is only incremented if the AND expression fails, not when it succeeds. If the AND succeeds and the OR isn't evaluated, m still needs to be set to true. In your example it remains zero if the AND succeeds.

This is a closer match to the functional behavior:

/* m = ++i && ++j || ++k; */
++i;
++j;

if (i != 0 && j != 0)
{
    m = 1;
}
else
{
    ++k;

    if (k != 0)
    {
        m = 1;
    }
    else
    {
        m = 0;
    }
}

no one will understand the example until after they already understand precedence, and using it to explain precedence will only serve to confuse the beginner.

well, i guess you made your point. :D

This article has been dead for over six months. Start a new discussion instead.