c++ - swap with non-const reference parameters -
i got [error] invalid initialization of non-const reference of type 'float&' rvalue of type 'float'
#include <stdio.h> void swap(float &a, float &b){ float temp=a; a=b; b=temp; } main() { int a=10, b=5; swap((float)a, (float)b); printf("%d%d",a,b); }
vlad correct, why cast float? use int values. however, if have reason doing way, must consistent in cast , references:
#include <stdio.h> void swap(float *a, float *b){ float temp=*a; *a=*b; *b=temp; } int main() { int a=10, b=5; swap((float*)&a, (float*)&b); printf("\n%d%d\n\n",a,b); return 0; } output:
$ ./bin/floatcast 510 when pass address function, must take pointer argument. void swap(float *a,.. when need reference address of variable (to pass pointer), use address of operator &. when handle values passed pointer, in order operate on values pointed pointer must dereference pointer using * operator. putting together, code above. (much easier use int... :)
c++ refernce
if understand want in comment, want this:
#include <iostream> // using namespace std; void swap(float& a, float& b){ float temp=a; a=b; b=temp; } int main() { int a=10, b=5; swap ((float&)a, (float&)b); std::cout << std::endl << << b << std::endl << std::endl; return 0; } output:
$ ./bin/floatref 510
Comments
Post a Comment