c++ - reference to a non-existent variable will be a error, but why doesn't this cause any error? -


i got question function below may result in run time error. why? code :

int& sub(int& , int& b){ int c = - b ; return c ; } 

how can write code in main there run-time error?? thanks!!

as it's undefined behaviour, there no guaranteed portable error.

but here , example, betting on gfact nested calls produce referred result overwritten.

int = 5, b=4, c=2;  int r = msub(a, msub(b,c)); cout << "should 3: "<<r<<endl; // output depends on compiler. received 0, incorect ! 

here online demo.

needless such errors extremely nasty ! happens here ?

  • the compiler first calls msub(b,c) resutl temporary reference former local variable on stack. @ moment, there's high probability, computed value of 2 still there, if temporary variable doesn't exist anymore.
  • then compiler calls msub(a, ...) using reference. call change stack, overwriting value referred to.
  • so there's no segfault, no horror (in simple compiler specific case), computed value inacurate.

i've tried describe general principle of problem:

enter image description here


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -