Given:
int i, j = 1;
Is the value of i defined? If so, what is it?
I suspect this is a duplicate, but it's somewhat hard to search for - if anyone can find it let me know.
Global variables are initialized by
default to their default values (0
for int)
Local variables are not initialized
by default
For example:
#include <iostream>
int a, b=1; // a=0, b=1
int main(void) {
int p, q=1; // p=undef, q=1
return 0;
}
proof for local variables:
#include <iostream>
int main(void) {
{
int x = 99; // change stack where a would be
}
int a, b=0;
std::cout << a << std::endl;
return 0;
}
If this code is in global scope, then i will be 0. Otherwise i is not defined.
No, it's not defined, and the compiler should complain if you try to use it, depending on the language.
If this is defining local variables then the value of i won't be defined.
The code you showed is equivalent to:
int i;
int j = 1;
that means, that i is defined, but not initialized.
i will be undefined. This leads to undefined behaviour if you try to use i without assigning it something.
Any good compiler will warn you about stuff like this. Using an undefined variable of type int might be harmless enough, but don't use undefined pointers.
Perhaps not today, but some time ago, before sufficient hardware and software protection, you could damage your machine's BIOS by using pointers with uninitialized variables.
Moral of the story: if it isn't initialized, don't use it.
The variable i can contain anything from 0 to garbage.
please refer to the following link
http://www.intap.net/~drw/cpp/cpp03_02.htm for more information
int i is a definition statement, but it is not assigned with a value.
Extern int i is declaration.
Related
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.
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.
If there is a global variable and the function has a parameter with the same name, and desired result is the sum of the local and global variable, how can we refer the global function in this particular situation? I know its not good idea to do so. But asking just for curiosity.
int foo = 100;
int bar(int foo)
{
int sum=foo+foo; // sum adds local variable and a global variable
return sum;
}
int main()
{
int result = bar(12);
return 0;
}
By far the best choice is to rename the function parameter so it does not conflict with the global variable, so there is no need for circumventions.
Assuming the rename option is not acceptable, use ::foo to refer to foo at the global scope:
#include <iostream>
int foo = 100;
int bar(int foo)
{
int sum = foo + ::foo; // sum adds local variable and a global variable
return sum;
}
int main()
{
int result = bar(12);
cout << result << "\n";
return 0;
}
Collisions between local and global names are bad — they lead to confusion — so it is worth avoiding them. You can use the -Wshadow option with GCC (g++, and with gcc for C code) to report problems with shadowing declarations; in conjunction with -Werror, it stops the code compiling.
Use ::foo - but REALLY don't do that. It will confuse everyone, and you really shouldn't do those sort things. Instead, rename one or the other variable. It's a TERRIBLE idea to use the :: prefix to solve this problem.
Best practice is to always name global variables with a leading lower case "g" as in gX gY.
It is never clear what you should name your variables at the beginning though.
::foo . That's a cool trick.
The below code generates an error when i run it but if i declare at-least one variable outside the loop the code works fine.Why can't i declare both the variables in the loop itself?
Error:
#include<iostream>
#include<conio.h>
using namespace std ;
int main()
{
for(int j=0,int i=0;i<4&&j<2;i++,j++)
{
cout<<"Hello"<<endl ;
}
getch() ;
return 0 ;
}
Works Fine:
#include<iostream>
#include<conio.h>
using namespace std ;
int main()
{
int i ;
for(int j=0,i=0;i<4&&j<2;i++,j++)
{
cout<<"Hello"<<endl ;
}
getch() ;
return 0 ;
}
You can, but the notation for declaring two variables in a single declaration is like this:
int j=0, i=0;
with no second int.
(This is actually what your second version is doing; you might think it's assigning the already-declared i, but actually it's declaring a new one, whose scope is the for-loop.)
Because that's how the Standard defines the syntax. There's nothing "wrong" in particular with the idea, but apparently it was decided that you can only have one declaration in the initialization part.
If you want to declare multiple variables, use a comma to enumerate them (but this way, you can only declare variables of the same type):
for (int i = 0, j = 10; i < 10; i++, j--)
However, I'm not sure you should be doing this. After a certain point, this evolves into an unreadable mess.
Note that the given answers "only" handles making multiple variables of the same type.
If, for some bizarre reason, you would need to do multiple types, this is valid (though awful):
for(struct {int a; double b} loop = {0, 1.5}; loop.a < loop.b; loop.a++)
{
// Awful hacks
}
int& lameness()
{
int h=66;
return h;
}
int main()
{
int c;
c = lameness();
cout<<"c is "<<c<< endl;
system("pause");
return 0;
}
Why does this work? int h is a local variable and shouldnt h be destroy once it exits function scope?
If i change my function to this it works without warning. Is this safer in any way?
:
int& lameness()
{
int h=66;
int &a = h;
return a;
}
Yes. But the wonderful thing about undefined behavior is that what actually happens is... undefined. Destroying an int actually doesn't involve doing anything at all, so if nothing reuses that spot on the stack, the value is going to still be there. That's what makes this kind of thing so frustrating -- often it seems to work, until you make some small, seemingly unrelated change and it stops working!
It works by coincidence, check this:
http://www.velocityreviews.com/forums/t285367-return-reference-to-local-variable.html
Basically, it returned the right value due to the memory still being set to that value. Sometimes in the future, that might not be the case. Don't do this.
It does not work. It is undefined behavior. Your skepticism was right on: the lameness function is an error, and some compilers would flag it as such. Nonetheless, a compiler may be "conforming" and still "allow" this code...such is the "lameness" of C and C++.
It is destroyed. It happens to work because memory that h was stored in hasn't been overwritten by the time you print the value.
It only works for you by coincidence, and because your code takes a copy of the value in the reference before doing anything else. It is not guaranteed to work.
You could see it failing with:
#include <iostream>
using namespace std;
int& lameness()
{
int h=66;
return h;
}
int main()
{
int &c = lameness();
cout << "c is " << c << endl;
return 0;
}
Of course, I had to ignore compilation warnings:
x.cpp: In function ‘int& lameness()’:
x.cpp:5:13: warning: reference to local variable ‘h’ returned [enabled by default]
x.cpp: In function ‘int main()’:
x.cpp:12:28: warning: ‘h’ is used uninitialized in this function [-Wuninitialized]
The output was:
c is 0
This happens because by the time c is passed to the I/O system, the space that was once h in lameness() has been reused for other variables, thus scratching the 66 that was stored in the space. In fact, even your original code produces 0 on my machine.