Logic behind modular function - c++

I do not understand why mysteryfunction(y) will equate to 40
when i int mysteryFunction(int, int =2). Anyone can explain to me?
Best, MM
#include <iostream>
using namespace std;
int mysteryFunction (int, int = 2);
int main()
{
int x = 10, y = 20;
cout << mysteryFunction (y);
}
int mysteryFunction (int x, int y)
{
return x * y;
}

In the declaration ofmysteryFunction() the second parameter is assigned a default value of 2, so if you call it only with one argument the second argument y will be 2.
Hence doing mysteryFunction(20) is basically the same as doing mysteryFunction(20, 2), which according to your code should return 20 * 2 = 40.
You may have been confused by the fact that the variable you pass to mysteryFunction() as its first argument is named y, same as the second parameter in its definition. However, those are completely different variables. In fact, it doesn't matter how you call them, only the position of arguments/parameters matters (along with their type if you take function overloading into account).

They will assume by default that y will be 2, thus when you fill in int x, it'll automatically take in (x,2).

In your declaration for mysteryFunction you give a default value of 2 to the second argument. Then you call it with only 1 argument so the default gets used for the second argument. So y=20 and 20 * 2 = 40. Don't mix up variable names. The x and y in main have nothing to do with x and y in mysteryFunction

Related

what does &fun() refer to in the program?

This is an example problem to demonstrate the use of references in c++. i'm a beginner and this is my first time learning about references. i don't understand why we use &fun(). what does it mean?
#include<iostream>
using namespace std;
int &fun(){
static int x = 10;
return x;
}
int main(){
int &y=fun();
y = 20;
cout<<fun();
}
output : 20
Equivalent syntax is int& fun().
So this function returns a reference to 'x' (that is static), so later in main you can modify it (y = 20 does change the x inside the function).
So another invocation returns 20, as the x had been changed.
int & means fun() is returning a reference to an int. In main(), that reference is assigned to y, and the value of y is modified to 20, also changing the value of x to 20.

What is the use of declaring an integer just after a function declaration?

I'm trying to learn C++ at my own pace via an online course. There is a function declaration and also there is an integer declaration just after that, which is q.
I don't understand what purpose the "q" serves in the code.
I tried to print out each step and it didn't make sense. I literally don't see the point of having a "q" in the foo function or what it does.
#include<stdio.h>
int foo (int q) {
int x = 1;
return (q + x);
}
int main (){
int x = 0;
while (x < 3) {
printf ("%i\n", x);
x = x + foo(x);
}
}
This code gives me
0
1
Seems like the "q" is incrementing x but I don't see the reason why because we didn't assign it to anything but just saying (int q)
In the code you posted, q is an argument to the function foo and foo will return the value of its argument (q) +1.
It is a call by value function call where foo() get call by passing the value to q variable.
If you not declare any argument in the function it will give an error because it's int q only to get the value from the main function.
So here when first time foo get call - it's return 1 and after that it's return 2 .
So in second time x=1+2=3
3>3 condition false.
It print only 0,1.
q is a parameter. That is, it is something in a function that accepts a value from the caller. As w3schools puts it:
Information can be passed to functions as a parameter. Parameters act as variables inside the function.
Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma:
Probably couldn't have explained it better myself.
This code gives me 0 1 Seems like the "q" is incrementing x but I don't see the reason why because we didn't assign it to anything but just saying (int q)
Ah, so, we actually did assign it to something. It might just not be noticeable. We did it when we called foo:
x = x + foo(x);
Here, by putting x between the parenthesis, we set q to the value of x (which appears to be 0, in this case). That means, q will have the value of x (0) inside the function call.
We also could have set it to something else, like 3:
x = x + foo(3);
Here, q is set to 3, because 3 is inside the parenthesis.
int foo (int q)
declares a function that takes an input parameter, q. The value q takes, in foo, depends on the value that is passed to it. In this case, when you call it with:
foo(x)
You state: run the code in foo, but give to q, upon entering the function, the value of x in main(). When you start programming, at first, this is misleading as q and x appear to be different variable. You'll get used to it.
You must also realise that the x in foo has nothing to do with the x in main. Those are different variables.
Thank you for all your answers and comments.
It seems like the q is the argument passed in and x is just there for representing an integer (redundantly).
It'd have been better if the code just used the integer 1 as:
int foo (int q) {
return (q + 1);

Why can't my function access and modify the variable passed to it?

i have written this little program to explain my point and my variable a remains unchanged it prints 4. I later learned that I need to use pointers or references; why is that?
#include <iostream>
void setToTen(int x) { x = 10; }
int main(){
int a = 4;
setToTen(a);
std::cout << a << std::endl;
}
In C++ arguments to functions are passed by value. This means that when you write
setToTen(a);
the parameter int x in setToTen is given a copy of the value stored in the variable a. In other words, you're not actually handing off the variable a into the setToTen function. Instead, you're giving a copy of that value to setToTen, so the changes made in that function affect the copy rather than the original.
On the other hand, if you change setToTen so that it takes its parameter by reference, like this:
void setToTen(int& x) {
x = 10;
}
the story is different. Here, calling setToTen(a) essentially hands the variable a into the function setToTen, rather than a copy of the value. That means that changes made to the parameter x in setToTen will change the variable a.
Your code requests a copy of x by having the signature void setToTen(int x).
Being able to take things by copy means that reasoning about the behavior of a function is far easier. This is true both for you, and for the compiler.
For example, imagine this:
int increase_some( int x, int y, int z ) {
for (int i = 0; i < y; ++i )
x+=z;
return x;
}
because x y and z are copies, you can reason about what this does. If they where references to the values "outside" of increase_some, the bit where you x+=z could change y or z and things could get crazy.
But because we know they are copies, we can say increase_some returns x if y<=0, and otherwise returns x+y*z.
Which means that the optimizer could change it to exactly that:
int increase_some( int x, int y, int z ) {
if (y<=0) return x;
return x + y*z;
}
and generate that output.
This is a toy example, but we took a complex function and turned it into a simple one. Real optimizers do this all the time with pieces of your complex function.
Going one step further, by taking things by immutable value, and never touching global state, we can treat your code as "functional", only depending on its arguments. Which means the compiler can take repeated calls to a function and reduce them to one call.
This is so valuable that compilers will transform code that doesn't have immutable copies of primitive data into code that does before trying to optimize -- this is known as static single assignment form.
In theory, a complex program with lots of functions taking things by reference could be optimized this same way, and nothing be lost. But in practice that gets hard, and it is really easy to accidentally screw it up.
That is the other side; making it easier to reason about by people.
And all you have to embrace is the idea of taking arguments by value.
Function parameters are function local variables that are not alive after exiting function.
You can imagine the function definition and its call
int a = 4;
setToTen(a);
//...
void setToTen(int x) { x = 10; }
the following way
int a = 4;
setToTen(a);
//...
void setToTen( /* int x */ ) { int x = a; x = 10; }
As it is seen within the function there is declared a local variable x which is initialized by the argument a. Any changes of the local variable x do not influence on the original argument a.
If you want to change the original variable itself you should pass it by reference that is the function will deal with a reference to the variable. For example
void setToTen(int &x) { x = 10; }
In this case you can imagine the function definition and its call the following way
int a = 4;
setToTen(a);
//...
void setToTen( /* int x */ ) { int &x = a; x = 10; }
As you see the reference x is as usual local. But it references the original argument a. In this case the argument will be changed through the local reference.
Another way is to declare the parameter as pointer. For example
void setToTen(int *x) { *x = 10; }
In this case you have to pass the original argument indirectly by its address.
int a = 4;
setToTen( &a );

C++ Defining Global Variable

Very simple question:
I was fiddling with basic C++ (being very new to programming) and I got into trouble while declaring a global variable to do some addition
#include <iostream>
int x,y;
int sum(int, int)
{
return x + y;
}
int main()
{
using namespace std;
cout << "The sum of 10 and 4 is: " << sum(10,4) << endl;
return 0;
}
Changing "int x,y;" to "int x,y = 0" has the same result: The sum equates to 0.
Could someone explain this odd behavior? Thanks!
Your function always returns the sum of global variables x and y, which are always 0. x and y are implicitly set to zero at the program startup. You never change their values, so they remain zero forever. The sum of two zeros is zero, no surprise here.
You pass 10 and 4 to your function, but the function itself completely ignores what is passed to it, i.e. it ignores its parameters (they are not even named). It always sums global x and y, which are always 0.
If you want your function to sum its arguments, you have to name the function parameters and use them
int sum(int a, int b)
{
return a + b;
}
And now you don't need any global variables at all. (main remains as is.)
Alternatively, if you so desire, you can get rid of the parameters completely and sum the global variables instead
int x,y;
int sum()
{
return x + y;
}
but in this case you will have to pass the values to sum through those global variables, not as function arguments
int main()
{
using namespace std;
x = 10;
y = 4;
cout << "The sum of 10 and 4 is: " << sum() << endl;
return 0;
}
This latter approach is here just for illustrative purposes. It is definitely not a good programming practice.
What you have in your code is a weird disconnected hybrid of these two approaches, which can't possibly work.
In order to fix the issue, the thing requires changing is the sum function.
int sum(int a, int b){
return a+b; //a,b here are referring to the inputs, while what you did was referring to the global variable..
}
Besides, try not to use global variables, usually you would end up with lots of troubles.
Another thing, I don't think your way of defining a function is correct. The inputs have to look like this instead:
int sum(int a, int b)
Unless you wanna declare the function first and provide the actual implementation later, you are not suppose to miss the name of the inputs!
when you are just globally declare the variables x,y ,they implicitly set to zero value.in your function definition,you are just giving the datantype of args, not the args names.so when you returning the sum of x,y ,it returns zero.and the value passed by the main function goes nowhere.
your program must look like this
#include<iostream>
int x,y;
int sum(x,y)
{
return x+y;
}
int main()
{
int v,a,b;
cout<<"values of a and b";
cin>>a>>b;
v=sum(a,b)
cout<<"their sum is"<<v;
}
when you explicitly define the value in second case
i.e int x,y=0;
you are just explicitly giving the value of value y to 0 while the x implicitly remains 0 and since you are not giving the args name,the ultimately result return biy the function is zero,
Seems that you only need x and y inside your add function, so make them local to the function. There is no reason to make them global. Follow the "least accessibility" idiom to prevent other parts of your program from mistakenedly modifying variables.
You might need a global variable supposed you want to define a well known parameter that every function needs to know and yet modifiable during run time. If you want it fixed, then a global constant would be more proper.
Hope that helps.

Assigning function to variable

Why assign a function to a variable? What's the point in assigning int x, y to ReadNumber() ? Is it for storing return value of function in a variable? Or is this just a way to pass arguments?
#include <iostream>
int ReadNumber()
{
using namespace std;
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void WriteAnswer(int x)
{
using namespace std;
cout << "The answer is " << x << endl;
}
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
return 0;
}
"why does he assign a function to a variable?"
He doesn't. This(note the brackets):
// vv
int x = ReadNumber();
assigns the returned value to x. The brackets mean, that the function is actually called - or the body is executed. That function has return x; at the end, so it returns the value of x which is assigned to x - the one in the main. Note that the x in main and x in ReadNumber are totally different.
Also, you can't assign function to a variable in C++ (you can use function pointers, but this is another thing)
"What's the point in assigning int x, y to ReadNumber() ?"
The returned value from ReadNumber is a temp value and it should be stored somewhere. So, that's why x and y are defined in the main, so that each of them stores the value, returned from ReadNumber. And each of these values can be different.
If, in main, there were no x and y, the returned values are unusable and cannot be accessed at all. And they are destroyed.
"Is it for storing return value of function in a variable? Or is this just a way to pass arguments?"
No any arguments here. Arguments are written inside the brackets ( () ) and here, there are no such when calling ReadNumber. So yes, they are for storing the returned values.
WriteAnswer does not have return at the and and it's defined as void - which means - no return value. That's why there's no such thing as
int x = WriteNumber( X + y )
But note, that here WriteNumber has argument. Just one, and it's the value of the calculated x + y. So, it's like:
int z = x + y;
WriteNumber( x );
Yes, it is storing the return value of the function.
The code calls the ReadNumber function twice first. ReadNumber reads a string from the console then returns it as an int. The code stores the two function returns. It then adds these two numbers together and passes it as an argument to the WriteAnswer function. The WriterAnswer function takes the argument that was passed in and prints it out.
int x = ReadNumber();
By this statement, the programmer wants to assign the return value of that function to the variable. If you check the function signature, you can see that it returns a value of type int .
ReadNumber() reads a number from the standard input and returns it.
int x = ReadNumber();
stores that value into x.
Actually the function is not assigned to variable
What happened is each time ReadNumber() is called, it returns a number of type int. that number can be used anywhere, like putting in a variable like x, and we can call it one more time and assign the next value returned to another variable like y
The result of ReadNumber() is assigned to x - not the other way around. ReadNumber() asks the user for a number and assigns it to x, then for another number and assigns it to y. Then main() adds them together and shows the user using WriteAnswer().
He doesn't assign the function/method itself but the results...
He's assigning the results of two successive calls of method: ReadNumber() to the variables x and y respectively.
So the returned value of ReadNumber() is what is assigned.
See the return type of ReadNumber() is int - the same type as the variables being assigned.
I've commented the method below to make it clearer:
int ReadNumber()
{
using namespace std;
cout << "Enter a number: "; // This line prints the command to the standard output
int x;
cin >> x; // This line reads a number and assigns it to x
return x; // This line returns the number and ends the method...
}