C++ Defining Global Variable - c++

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.

Related

How does a function know what inputs to draw from when labeled under different names?

How can int length and int array[] be labeled differently than int TOTAL and int scores, yet they are recognized as being the same in the average() function? I assumed they had to be called the same thing in order to be recognized?
#include <cs50.h>
#include <stdio.h>
float average();
const int TOTAL = 3;
int main(void)
{
int scores[TOTAL];
for (int i = 0; i < TOTAL; i++)
{
scores[i] = get_int("Score: ");
}
printf("Average: %f\n", average(TOTAL, scores));
}
//int array [] same as saying int scores [] ?
//int 'length' same as saying 'TOTAL' ?
float average(int length, int array[])
{
int sum = 0;
for (int i = 0; i < length; i++)
{
sum += array[i];
}
return sum / (float) length;
}
Variable names in most programming languages have a certain "scope" that they apply to. In C/C++, scopes are often determined by regions between a { and } character, e.g. a function scope or a loop scope within it.
In this specific example, TOTAL is defined in the "global" scope. Anything after that line can see and access that variable. This is generally considered bad practice, because it "pollutes" the global scope. Imagine, what would happen if you added someone else's code that also defined TOTAL to be something else? Or worse, forgot to define it but used it anyway? Nothing good, I promise you.
All other variables in this example are defined in their own "local" scope. The name scores is usable int main(void) { int scores... <HERE> } <but not here>. Likewise, the name array is usable average(int length, int array[]) { <HERE> } <but not here>.
But how do you get data from one function to another? You call the function! From main, when you call average(TOTAL, scores), you are referring to the name TOTAL from the global scope, and scores from main's scope, and passing them as "arguments" or "parameters" to the function average. The function average defines its own names for those arguments, but they will still contain the data from the variables used where it is called.
This is an essential property of most programming languages. Without it, function callers would need to make sure their names don't conflict with the internal ones used by the functions they call, and vice-versa. The relevance of this mechanism might be more obvious with a different example:
// convert a temperature in celcius to farenheit
float c2f(float celcius) {
return 1.8f * celcius + 32.0f;
}
// print the computer temperature sensor values in farenheit
void print_computer_temperatures(temperatures_t temps) {
float gpu_temp = c2f(temps.gpu);
float cpu_temp = c2f(temps.cpu);
float chipset_temp = c2f(sys()->GetTemp(CHIPSET));
float chassis_temp_c = -1;
CoolerMasterQueryChassisTemp(&chassis_temp_c);
float chassis_temp = c2f(chassis_temp_c);
printf(...);
}
In this case, the arguments are called positional.
This means, that when you define a function (float average(int length, int array[]){...}), length will be the firs argument and array will be the second. These names are not global and exist only inside the function.
When you call the function (average(TOTAL, scores)), you pass global (availiable from everywhere) variable TOTAL as the first argument, and a local for main function variable scores as the second argument.
length is not the same as TOTAL, it just gets the value of TOTAL when the function is called. Same for array and scores.

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.

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 );

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

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.

"invalid use of non static member function" What is this?

EDIT: thanks for all the speedy responses, I have a much better understanding of this concept now. Also, I'll try to make my error messages more clear next time.
EDIT: updated with my newest code. the error happens on line 18. Also, I'm beginning to wonder if my latest issue has to do with the original class itself?
I'm trying to teach myself classes and objects in C++. I did it once by just declaring a void function, outputting something on the screen, calling the object in main and everything worked fine.
Now, I wanted to expand upon this and make a simple addition thing. However, I get a couple errors on Code Blocks:
error: invalid use of non-static member function 'int Addition::add(int, int)'
error: no matching function for call to 'Addition::add()'
Here's my code:
#include <iostream>
using namespace std;
class Addition {
public:
int add (int x, int y) {
int sum;
sum=x+y;
return sum;
}
};
int main()
{
int num1;
int num2;
int ans=addobj.add(num1,num2);
Addition addobj;
addobj.add(num1,num2);
cout<<"Enter the first number you want to add"<<endl;
cin>>num1;
cout<<"Enter the second number you want to add"<<endl;
cin>>num2;
cout<<"The sum is "<<ans<<endl;
}
One of the most important things, a developer should learn to do is to read compiler's messages. It's clear enough:
error: no matching function for call to 'Addition::add()'
Your function in your class is
int add (int x, int y)
it takes 2 arguments and you pass none:
addobj.add();
You have 2 options:
create and initialize x and y inside your main and pass them as arguments
make add without parameters, create x and y inside add's body, as their values are taken from user input.
In this case, as the function's name is add, I'd chose the first option:
declare int x, y; inside your main
read the user input inside the main (the part, where you use cin and cout)
pass the x and y as arguments to add like this: addobj.add( x, y );
store the result (if needed), like this: int result = addobj.add( x, y );
You declared a method add(int, int) that takes two integers as arguments; you have to supply those arguments when you call it. It would be nice to print the returned value, as well:
Addition addobj;
std::cout << addobj.add(1, 2) << std::endl;
Your add function takes two arguments, yet you call it with none, so no matching function could be found. You must call the function as it was declared, i.e.,
addobj.add(1, 2);
Your function takes two arguments and yet you call it without providing them. You need to provide the two integer arguments that your function requires. To be useful you should store the result too. Something like this
int a = 1;
int b = 2;
int result = addjobs.add(a,b);