In Python, yield
is used for generation. For example:
def func():
i =0
while True:
i += 1
yield i
If I remember Python correctly, this should allow this function to basically pause execution and get called over and over again. This can generate some sequence like {0,1,2,3...}
.
On the other hand, return
just returns a single value and ends execution:
def func():
i =0
while True:
i += 1
return i
This should always return 0
, since the function ends execution completely so i
goes out of scope every time.
On the other hand, C++ has no direct real equivalent to yield
as far as I'm aware (except for apparently in the new C++20, which is adding an equivalent), where as it does have an equivalent (in all versions) to return
here. It is, of course, called return
.
That said, C++ can achieve something similar to our yield example using static variables:
int func() {
static i = 0;
return i++;
}
However, that is not to say that static variables are replacements for yield
in C++. It's just that you can sort of achieve the same thing in C++ with static variables in this (and possibly other) example(s).
So, in short, return
ends execution of a function in both languages whereas yield
allows a function to sort of resume execution. There is no real equivalent for Python's yield
in C++ until at least C++20.