0

Increment subsequent output.

Is there a way to increment every subsequent output of h, without calling the function m(h) every time before outputting h? (I.e, calling m(h) once and every other cout << h; increasing by 1. https://code.sololearn.com/c68I5rc15z82/?ref=app

7th May 2021, 12:05 PM
Infinite
Infinite - avatar
6 Respuestas
+ 1
You can just write this: cout << h++ << endl; That will print h and increase it by 1
7th May 2021, 3:09 PM
Hape
Hape - avatar
+ 1
I think that is not possible. At least not easily. The main problem is that h is of integral type int which means it only stores the content (a number) of the variable. So how should those calls to cout << h know that you want the function m to be called on h. For this to work you would have to change how cout outputs data for an integral type which is at least complicated. The only other way I can think of how this could be done is to define a custom type (class or struct) and overload the operator<< for output streams. Then you can call any arbitrary function on the variable before it is printed. But that comes at the cost of wrapping a single int value inside a custom type which is probably not really worth it. I made a code which shows how that could be done but this is still not really the exact behavior you wanted because that would be even more complicated (you would have to store which function to call and so on) https://code.sololearn.com/cA24A3A13a25/?ref=app
7th May 2021, 4:03 PM
Hape
Hape - avatar
0
Hape thanks, but this wasn't what I meant. Doing this, I wouldn't need to call the function m();.
7th May 2021, 3:27 PM
Infinite
Infinite - avatar
0
I am not quite sure what exactly you are trying to do. But if you want to call the function m you can of course also write this: cout << m(h) << endl;
7th May 2021, 3:34 PM
Hape
Hape - avatar
0
Hape it should be like int main (){ int h=5; m(h); cout << h; // output: 6; cout << h; //output: 7; cout << h; //output: 8; } // By calling m(h) just once in the main function.
7th May 2021, 3:39 PM
Infinite
Infinite - avatar
0
Hape thanks very much for the help.
7th May 2021, 6:18 PM
Infinite
Infinite - avatar