Beginner Programmer c++(local vs global variable declaration) - c++

I'm new to programming. I was trying to get the sum of the equation added to the previous value when I noticed some strange behavior.
If I declare int result inside int main () then I get a blank answer, but if I declare int result outside int main () then I get these values: 6,11,16...91,96,101. It doesn't make sense to me since I have no other function.
Why does this happen?
#include<iostream>
using namespace std;
int main ()
{
int y =1;
int result;
while (result <100)
{
result = y +5;
cout << result << ",";
y = result;
}
}

Within a function, int result; declares a variable named result, but doesn't initialize it to any particular value. Until you assign it a value it could be anything, and the behavior when reading from it is undefined. Thus when you read its value in your while condition it could be anything; your loop may execute or it may not. You need to supply an initial value for result to make the behavior of your program well-defined:
int result = 0;
Unlike local variable, global variables are defined to be initialized to a default value when no initial value is explicitly provided, so when you read the value of result in your while condition, it is 0, and your loop executes.

Related

How can I initialize a variable but when said function is initiated the value of the variable is not reset?

I've made this example to show what I'm talking about. I want to know if there is a way to run through main() without resetting value to 0.
int main(){
int value = 0;
value++;
cout << value << endl;
main();
}
Before answering the question, your example has two big problems
Calling, or even taking the address of, main is not allowed.
Your function has infinite recursion which makes your program have undefined behavior.
A different example where value is saved between calls could look like this. It uses a static variable, initialized to 0 the first time the function is called, and is never initialized again during the program execution.
#include <iostream>
int a_function() {
static int value = 0;
++value;
if(value < 100) a_function();
return value;
}
int main(){
std::cout << a_function(); // prints 100
}
If you want to keep the variable value local to the main function, you can declare it as static int value = 0;.
As has been pointed out in various comments though, recursively calling any function without an escape mechanism like you are is a bad idea. Doing it with main is a worse idea still apparently not even possible.

Static Float variable only stores highest value assigned; need it to store most recent

This seemed to be the closest; my program is similar, but my question is slightly different.
I'm having trouble seeing why the output of this program is "5,5" instead of "5,4". I was under the impression that the value "4" was immediately assigned to the "static float" variable "m" once the maxvalue function was called.
If that is the case, why is 5 the output instead of 4?
#include <iostream>
using namespace std;
float keepmax(float f) {
static float m = f;
if(f>m)
m = f;
return m;
}
int main() {
cout << keepmax(5) << endl;
cout << keepmax(4) << endl;
return 0;
}
In C++, a static variable declared within a function scope will be created and initialized once for all non-recursive calls to that function.
NOTE: Recursive calls effect on static variable initializations are undefined behavior according to the C++ standard.
C++ Standard 6.7 Paragraph 4:
If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
Example:
int foo(int i) {
static int s = foo(2*i); // recursive call - undefined
return i+1;`
}
The first time your function enters the keepmax function, your static float m variable is initialized to the value passed in, which in this case is 5. From this point on, the variable has been created and initialized and the static float m = f; statement will, in essence, be skipped over.
The second time your function enters keepmax, m still has the value 5 from the first call, and the execution (essentially) "jumps over" the static float m = f; statement and goes directly to the comparison. Because m equals 5 and f equals 4, the comparison (f>m) is false (as 4 is not greater than 5), and the subsequent assignment never occurs.
I was under the impression that the value "4" was immediately assigned to the "static float" variable "m" once the maxvalue function was called.
You where under wrong impression, that is not assignment but initialization, and it only happens once when execution flow goes through that code the first time, that's how local static variables work. If you want that variable to change value every time, you need to make it non static:
float m = f;
or you can also make assignment happen every time:
static float m;
m = f;
but then it does not make any sense to make this variable static (unless this assignment is done conditionally)
Because the static will continue holding its value even after the function has returned. Hence when you call it the second time, it still retained '5' as the highest value.

References - Why do the following two programs produce different output?

I recently read about references in C++. I am aware of basic properties of references but I am still not able to figure out why following two programs produce different output.
#include<iostream>
using namespace std;
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
This program prints 30 as output. As per my understanding, the function fun() returns a reference to memory location occupied by x which is then assigned a value of 30 and in the second call of fun() the assignment statement is ignored.
Now consider this program:
#include<iostream>
using namespace std;
int &fun()
{
int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
This program produces the output as 10. Is it because, after the first call, x is assigned 30, and after second call it is again overwritten to 10 because it is a local variable? Am I wrong anywhere? Please explain.
In the first case, fun() returns a reference to the same variable no matter how many times you call it.
In the second case, fun() returns a dangling reference to a different variable on every call. The reference is not valid after the function returns.
When you use
fun() = 30;
in the second case, you are setting the value of a variable that is not valid any longer. In theory, that is undefined behavior.
When you call fun() the second time in the second case, the variable x is set to 10. That is independent of the first call to the same function.
Just adding to what has been said. The reason behind the first case's behavior is because it is a static variable, which has a static duration. Static duration means that the object or variable is allocated when the program starts and is deallocated when the program ends.
This means that once x in the first case has been initialized the first time with 10, the next function call will ignore static int x = 10; because x cannot be instantiated again, as it has already been allocated, and will simply proceed to return x;, which will be the same x that was assigned 30 in main.
Basically, your understanding is right, except for in 2nd case, you're processing a dangled reference of the local variable has been invalid, which is undefined behaviour, means anything is possible. What you said is just one of the possibility, it also could result in others, such as getting a random number, program crash, etc.

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...
}