Operand order in C

Say you have x = exp1 + exp2 in c. It could be evaluated by first evaluating exp1, then exp2 and adding the results, but first it can evaluate exp2.

How do you know which side is ranked first? I would like to make x = 1/2 depending on which one was rated first.

Any ideas?

+4
source share
2 answers

Ok, you can do it like this:

#include <stdbool.h>
#include <stdio.h>

static int first(int value)
{
  static bool first = false;
  if (!first)
  {
    first = true;
    return value;
  }
  return 0;
}

int main(void)
{
  const int x = first(1) + first(2);
  printf("got %d\n", x);
}

On ideone.com I received 1.

Note that this does not prove anything, since there is no specific behavior. Draft C99 states (in 6.5 terms, paragraph 3):

. 72) , ( - (), &&, ||, ?: ), , , .

+5

, ?

. C11 6.5/3:

, , . 86)

...

86) , , .

" " , , : || && ?: ,, .

, , . , , , , . , .


, , ( ), :

#include <stdio.h>

int func(void)
{
  static int x=0;
  return x++;
}

int main (void)
{
  printf("%d", func() << func());
}

0<<1 == 0 ( ), 1<<0 == 1 ( ). .

0

Source: https://habr.com/ru/post/1673611/


All Articles