Recently encountered a problem where multiple values need to be returned through a function. But C and C ++ cannot return multiple values. So there is a solution.
The online method is messy and there are two alternative methods:
1. Using the side effects of the function, the returned value is defined outside the function and modified within the function, generally void function.
For example, 1.1 enter x and y to find the modified x, y
# Include <iostream> swap (* p, * temp = ** p = ** q = cin> a> cout <a <B <swap (a, B ); cout <a <B <}View Code
For example, 1.2 enter a, B, c to calculate x, y, z.
Omitted
For example, 1.3 enter x [] to find the modified x []
# Include <stdio. h> # include <stdlib. h> * bbb (* I = (I <* p1 + = * p1 ++ I ++ a [] = {,,, I = (I <printf (I ++}View Code
For example, 1.4 enter x [] for y []
Omitted
2. Package and return the returned value, for example, an array name, pointer, and struct.
In Example 2.1, an array name is returned.
<Stdlib. h> * aaa (I = (I <+ = ++ * a [] = {, = I = (I <++View Code
In Example 2.2, a pointer is returned.
# Include <stdio. h> # include <stdlib. h> aaa (* I = (I <* p ++ = I ++ * a [] = {,,, px = I = (I <printf (I ++}View Code
In Example 2.3, a struct is returned.
Omitted
(If anyone is interested, try to write one)
A function with a returned value must be accepted by a pointer, and the address of the variable defined in the previous main function is received. That is, as long as the function is called, the value of the variable is changed, and you do not need to define a pointer variable to receive the variable. From this we can conclude that all functions with return values can be changed to void () type function. (Example 2.2 can be abbreviated as example 1.3)
To sum up
We can see that no matter how you return, no matter whether you return or not, pointers are almost used. Some people may say that the use of pure Arrays can also be implemented. LZ used arrays before, but now I think it was stupid. The reason will be known to anyone who uses pointers. In fact, the above many methods are simply described as follows:
Use Pointer.
The pointer is very powerful. LZ was greedy before and didn't learn much. Recently I learned C and picked it up again. I must learn this. Use well.