E
E
Egorithm2016-12-01 23:14:41
C++ / C#
Egorithm, 2016-12-01 23:14:41

Why is it bad manners?

This is from K&R:

a[i] = i++; // Значение i при присваивании неопределено

I can't understand why.
The idea arose that for C any operation is essentially a function call.
That is, for example, it is not defined here which one will be called first, but this is not important.
x = func_1() + func_2();
I thought that here it is not defined what will happen first: increment or address calculation.
But postfix notation defines it. It should copy the value into the variable and make an increment over it, and after all the operations, replace it.
Why then is the value of i not defined in the assignment?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2016-12-02
@EgoRusMarch

Alexey : Evgeny Shatunov :
People who know how to google, but do not understand what they are talking about, give answers! Every day on the toaster!
They can google an article that says about the same thing as the question asked, but, alas, not quite.
And neither in the article nor in the answers does not appear the correct answer.
And the correct answer is in the second, non-obvious part of the clause of the standard describing expressions (C89: 3.3:2, C99: 6.5:2):

Between the previous and next sequence point an object shall have its stored value
modified at most once by the evaluation of an expression. Furthermore, the prior value
shall be read only to determine the value to be stored.

Those. if the object is modified, then it can be read for the sole purpose of computing the value to be written to it. Code a[i] = i++; reads the value of the mutable variable i for another purpose: accessing an array element by index, the result of which does not affect the final value of i -- and this is enough for such code to fall into the UB category.

M
Maxim Moseychuk, 2016-12-02
@fshp

That is, for example, it is not defined here which one will be called first, but it does not matter .
x = func_1() + func_2();

Here you are deeply mistaken.
#include <iostream>

int x = 2;

int func_1() {
    x *= 10;
    return x;
}

int func_2() {
    x += 10;
    return x;
}

int main() {
    std::cout << func_1() + func_2() << std::endl;
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question