Question about variable

Hi, I have one question.
I have created integer variable with name y. I assigned value like this:
1
2
int x = 2;
int y = x++ + x;


Later I wanted to add some more stuff into that variable like this:
 
y = y+2;


But it doesn't compile. Is that mean that I can't assign anything more to y? I have to write everything in one line? Tell me. Thanks :)
It compiles fine.
1
2
3
4
5
6
int main()
{
int x=2;
int y = x++ + x;
y = y+2;
}

http://ideone.com/9QLER
Oh. I put variables outside main. Is that big difference?
Putting a variable outside of main gives it a global scope which is usually not something we like to practice unless absolutely nessesary (which is almost never the case.

However, pertaining to your post, in your initialization of y you use x++. This changes the value of x. We cannot change values in the global scope as it is not part of the main program. We can only initialize values.
So it's true, that this is quite similar to Java. Where variable, created in method is local?
Please do not think in Java when coding C++. You will end up writing Java in C++, which will be truly horrible. :)
Last edited on
Topic archived. No new replies allowed.