C++/easy one


I have to write a simple C and C++ function that includes the following sequence of statement:

x = 21;
int x;
x = 42;

Is this possible in the sequence and if so how and what are the results?

The code, as you have it, won't work. You can't use a variable before you initialize it. I.E., you can't say 'x=21;' before you write 'int x;'. You could write 'int x = 21;', and that would work fine. In theory, what you have written would set the value of 'x' to 21, then re-initialize the variable (thus resetting its' value to some random memory address), and set the value of 'x' to 42. So, in theory, if the code above looked like:

//Using endl for readability if actually used
x = 21;
cout << x << endl;
int x;
cout << x << endl;
x = 42;
cout << x << endl;

Your output would look like:
some random memory address that looks like gibberish

But remember that since you haven't initialized 'x' in the code you've given me, the program won't compile, and thus won't work.

Best Of Luck,


All Answers

Answers by Expert:

Ask Experts


Alan F.


Having problems with any basic or intermediate parts of C++? I can answer those questions for you using simple English. I have been taking C++ in school for a couple years, so I still remember what it was like to be a beginner (especially with C++, which is a difficult language)!


I have a C++ web page that discuses the basics of C++. The address is: http://www.afweb.net/complang/

©2017 About.com. All rights reserved.