Inkrementace ne levé i pravé straně přiřazení

Re:Inkrementace ne levé i pravé straně přiřazení
« Odpověď #15 kdy: 06. 09. 2019, 11:11:50 »
Nic "nedefinovaneho" na tom neni. ++ je normalni funkce, akorat zapsana jako operator. Takze:

++i si prepiste jako
Kód: [Vybrat]
int incr_pre(int &i) { i++; return i; }
i++ prepiste jako
Kód: [Vybrat]
int incr_pos(int &i) { int tmp = i; i++; return tmp; }
a je to jasny.

Kód: [Vybrat]
a[i] = incr_pos(i); // a[i] = i++;
a[i] = incr_pre(i); // a[i] = ++i;
a[incr_pos(i)] = incr_pre[i]; // a[i++] = ++i;

Pro hnidopichy, ano neni to C, je to C++. Kdo chce C, at si prepise referenci na pointery.

Ani to tom tvem prepisu to nezacne byt definovane. Protoze volani/navrat funkce je sequence point ale = neni.


Re:Inkrementace ne levé i pravé straně přiřazení
« Odpověď #16 kdy: 06. 09. 2019, 11:14:53 »
Ondra Satai Nekola: priznavam, = bude problem.

Re:Inkrementace ne levé i pravé straně přiřazení
« Odpověď #17 kdy: 06. 09. 2019, 11:20:07 »
Nic "nedefinovaneho" na tom neni. ++ je normalni funkce, akorat zapsana jako operator. Takze:

++i si prepiste jako
Kód: [Vybrat]
int incr_pre(int &i) { i++; return i; }
i++ prepiste jako
Kód: [Vybrat]
int incr_pos(int &i) { int tmp = i; i++; return tmp; }
a je to jasny.

Kód: [Vybrat]
a[i] = incr_pos(i); // a[i] = i++;
a[i] = incr_pre(i); // a[i] = ++i;
a[incr_pos(i)] = incr_pre[i]; // a[i++] = ++i;

Pro hnidopichy, ano neni to C, je to C++. Kdo chce C, at si prepise referenci na pointery.
 
Sorry, ale nemáš úplně pravdu. V C++ je operátor++ normální funkce jen pro structy a classy. Pro inty a další vestavěné skaláry to funkce není. C++17 dodefinovalo nějaké situace, ale operace s inty stále nejsou normální funkce.

Stačí kouknout na https://en.cppreference.com/w/cpp/language/eval_order
Citace
1) If a side effect on a scalar object is unsequenced relative to another side effect on the same scalar object, the behavior is undefined.

i = ++i + 2;       // undefined behavior until C++11
i = i++ + 2;       // undefined behavior until C++17
f(i = -2, i = -2); // undefined behavior until C++17
f(++i, ++i);       // undefined behavior until C++17, unspecified after C++17
i = ++i + i++;     // undefined behavior

2) If a side effect on a scalar object is unsequenced relative to a value computation using the value of the same scalar object, the behavior is undefined.

cout << i << i++; // undefined behavior until C++17
a = i++;       // undefined behavior until C++17
n = ++i + i;      // undefined behavior
Obzvlášť poslední dva řádky první odrážky dobře ilustrují rozdíl mezi sčítáním intů a voláním funkce.