Sunday, 15 January 2012

c++ - Forward decleration changes function behaviour? -


I am learning C ++ and found just something strange that I have to understand (see comment on the 5th line of code) ):

  #include & lt; Iostream & gt; using namespace std; // Output A = 1 and B = 2 with this forward expression / output without this further expression A = 2 and B = 1 // Why ?? Zero swap (int a, int b); Int main () {int a = 1; Int b = 2; Swap (A, B); Cout & lt; & Lt; "A:" & lt; & Lt; A & lt; & Lt; Endl; Cout & lt; & Lt; "B:" & lt; & Lt; B & L; & Lt; Endl; System ("pause"); Return 0; } Zero swap (int a, int b) {int tmp = a; A = B; B = TMP; }  

Can anyone please explain this behavior? I thought that by default the c ++ value passes unless you use amperstand (& amp;) in front of the function parameter:

 Function swap (int and a, int and b) { 

First of all, all the swap functions do not swap original logic. Swaps copies of arguments that will be destroyed after the exit of the ceremony. If you want the function to actually swap original arguments then the parameter has to be declared as retrieval

  zero swap (int and a, int & b) {int Tmp = a; A = B; B = TMP; }  

If there is no forwarding declaration of your function in the program, it seems that the compiler chooses the standard function std :: swap which is the original Swaps the argument. Standard function std :: swap is considered by the compiler due to user directive

  using the namepsace std;  

If you remove it and delete the announcement next to your function, then the compiler will issue an error.

When your function has been forwarded, the compiler selects your function because it is the best match in the form of non-templates function.


No comments:

Post a Comment