c++ - Forward decleration changes function behaviour? -


i'm learning c++ , found strange understand (see comment on 5th line of code):

#include <iostream>  using namespace std;  // forward decleration output a=1 , b=2 // without forward decleration output a=2 , b=1 // why?? void swap(int a, int b);  int main() {      int = 1;     int b = 2;      swap(a, b);      cout << "a: " << << endl;     cout << "b: " << b << endl;      system("pause");      return 0; }  void swap(int a, int b) {     int tmp = a;     = b;     b = tmp; } 

can explain behaviour please? thought default c++ passes value unless use amperstand (&) in front of function parameter this:

function swap(int &a, int &b) { 

first of swap function not swap original arguments. swaps copies of original arguments destroyed after exiting function. if want function indeed swap original arguments parameters have declared referemces

void swap(int &a, int &b) {     int tmp = a;     = b;     b = tmp; } 

when there no forward declaration of function in program seems compiler selects standard function std::swap swaps original arguments. standard function std::swap considered compiler due using directive

using namepsace std; 

if remove , remove forward declaration of function compiler issue error.

when forward declaration of function present compiler selects function because best match non-template function.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

gradle error "Cannot convert the provided notation to a File or URI" -