In c++: what is the difference between initializing a variable in a function versus declaring it in the function header? -
is difference in can them?
also, how can pass result of variable in function function? recently, had variable wasn't passing code in parent function other function.
void add(int a, int b)
vs
void add(int a) int b; a+b;
and passing result of variable parent function function:
void add(int a, int b, double c) a+b=c; void divide(double c, int d, double e) c / d = e;
there big difference between these 2 functions (i added absent details)
void add(int a, int b) { int c = + b; } void add(int a) { int b = 10; int c = + b; }
in first case can call function passing 2 arguments. example
add( 2, 5 );
and inside function variable c have value depending of 2 arguments (if = 2, b = 5 c = 7).
in second case can call function passing 1 argument
add( 2 );
so if specify argument 2 c equal 12.you can not change value of b calling function because have no access it.
take account code not compiled
void add(int a, int b, double c) { + b = c; }
you may not assign expression a + b
if need pass result 1 function can pass through function return object.for examploe change return type void
int
in first function
int add(int a, int b) { int c = + b; return c; }
in case can pass result "parent" function. example
#include <iostream> int add(int a, int b) { int c = + b; return c; } void add(int a, int b, double c) { std::cout << + b + c; } int main() { int x = 10; int y = 20; int z = 30; add( x, y, add( x, z ) )' }
the output equal 70 ( x + y + (x + z ) ). in example there 2 overloaded functions name add 1 of has 2 parameters , other has 3 parameters.
also can function result using parameters passed either reference of using pointers.
for example
#include <iostream> void add(int a, int b, double &c) { c = + b; } int main() { int x = 10; int y = 20; int z; add( x, y, z ) ); std::cout << "z = " << z << std::endl; }
the result z = 30.
if use poinetrs code as
#include <iostream> void add(int a, int b, double *c) { *c = + b; } int main() { int x = 10; int y = 20; int z; add( x, y, &z ) ); std::cout << "z = " << z << std::endl; }
the result same 30.
Comments
Post a Comment