[Cs3] operator++
Mikhail Nesterenko
mikhail at cs.kent.edu
Wed Jan 15 19:55:53 EST 2014
>
> In class we talked about how something like
>
> Int i = 0;
>
> ++i++;
> }
> Is syntactically illegal in C++, however I was wondering how C++ handles
> {
> Int i = 0;
> i.operator++(i++);
> }
>
operator++ does not accept integer as a parameter. Well, it does, but
it is a "dummy" integer (to be ignored) to distinguish the signatures
of prefix and postifx version of increment.
That is, the signatures are:
Number& operator++ (); // prefix ++
Number operator++ (int); // postfix ++
See this article in C++ FAQ for more info
http://www.parashift.com/c++-faq-lite/increment-pre-post-overloading.html
So, the above would not do what you are thinking anyway. Moreover, it
would fail to compile because "i" is declared integer (assuming "int"
is lower case) which is a primitive type for which dot-operator is not
applicable.
However, what I wanted to clarify is the difference between prefix and
postfix forms of the increment. In C++, prefix form returns an l-value
(assignable) while postfix form returns an r-value (not
assignable). However, both prefix and postfix forms need l-value as an
argument. Therefore, prefix form is stackable while postfix form is
not:
++++++i; // legal
i++++++; // not legal
The case of
++i++;
is curious. The precedence of the postfix form is higher than that of
the prefix form. Hence, in the above statement, postfix is evaluated
first, it returns an r-value, which is not allowed as an argument for
prefix form of the increment.
However,
(++i)++; // is legal
Below is an example program that demonstrates using the prefix form of
the increment as an l-value.
Thanks,
--
Mikhail
----------------------------------
// demonstrates that pre-increment returns an l-value
// Mikhail Nesterenko
// 1/15/2014
#include <iostream>
int main(void){
int i=0;
++i = 22 + 5;
(++i)++;
std::cout << ++--++i << std::endl;
}
More information about the cs3
mailing list