Reputation: 252
I hope the title of the post isn't too much of a mess. I'm reviewing some course material from last week, and there is just one thing I don't understand in regard to this particular structure and the add and subtract functions in it:
Structure ComNum
Dim Re As Double
Dim Im As Double
Function add(ByVal br As ComNum) As ComNum
add.Re = br.Re + Re
add.Im = br.Im + Im
End Function
Function subt(ByVal br As ComNum) As ComNum
subt.Re = br.Re - Re
subt.Im = br.Im - Im
End Function
End Structure
Sub Main()
Dim a, b, c As ComNum
a.Re = 2
a.Im = 3
b.Re = 4
b.Im = 5
c = a.add(b).add(b).subt(b)
Console.WriteLine("The second number added twice and subtracted once from the first number gives {0}+{1}i", c.Re, c.Im)
End Sub
Now, the way I understand functions is that once anything is returned from it, execution of the function stops at that exact line where the value is returned and nothing after it gets executed. According to that, it should add the real part and exit the function.
I know I'm missing a key thing here and I'd appreciate it if someone could explain this to me.
Upvotes: 2
Views: 1544
Reputation: 1322
The way you have this setup those functions are creating a new, empty ComNum structure each time you call them (named either add or subt based on the function name). Unless you manually return them early it will just default to returning the function named structure.
Function add(ByVal br As ComNum) As ComNum
add.Re = br.Re + Re
add.Im = br.Im + Im
End Function
Is basically doing the equivalent of:
Dim add As New ComNum
add.Re = br.Re + Re
add.Im = br.Im + Im
Return add
Though like Lars pointed out I'm not sure why you'd want this to be a function vs a sub. Using it the way you have it setup now requires you to do something like this to get the add/subtract values because you need to capture the returned ComNum object.
Dim a As New ComNum With {.Im = 1, .Re = 1}
'Im = 6, Re = 6
a = a.add(New ComNum With {.Im = 5, .Re = 5})
Doing something like this makes more sense to me.
Structure ComNum
Dim Re As Double
Dim Im As Double
Sub add(ByVal br As ComNum)
Re += br.Re
Im += br.Im
End Sub
Sub subt(ByVal br As ComNum)
Re -= br.Re
Im -= br.Im
End Sub
End Structure
Then you could just call it this way to update the struct without having to capture the returned values.
a.add(New ComNum With {.Im = 5, .Re = 5})
Edit: Knowing more now how the exercise is supposed to be performed I'd suggest something like this for the struct:
Public Overrides Function ToString() As String
Return String.Format("Re: {0} Im: {1}", Re, Im)
End Function
Then you could call the .ToString() method like this. Though, just a thought.
Console.WriteLine("The second number added twice and subtracted once from the first number gives {0}", c.ToString())
Upvotes: 3