By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,401 Members | 820 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,401 IT Pros & Developers. It's quick & easy.

C/C++ Function question

P: 1
Hello....I have to write a C and C++ function that includes the following sequence of statements.

x=21;
int x;
x = 42

I then have to run the program and explain the results.

I have never written code in C or C++, and the books that I have picked up are not helpful at all. Anyway, the code I have so far which is in C++ is

#include <iostream>
using namespace std;

int x = 21;

main()
{
int x;
x = 42;
}

I am not sure of where to go from here to implement that function, or where to even begin to write the thing in C. Any help would be appreciated. Thanks.
Jun 17 '07 #1
Share this Question
Share on Google+
1 Reply


Expert 10K+
P: 11,448
You're doing fine: you defined a global variable 'x' and you're hiding it with a local
variable 'x' in your main function. Better include the return type of main:

Expand|Select|Wrap|Line Numbers
  1. int x= 21;
  2.  
  3. int main() {
  4.    int x= 42;
  5. }
  6.  
The same code works for C too if you add a return statement at the end of the
main function:

Expand|Select|Wrap|Line Numbers
  1. int x= 21;
  2.  
  3. int main() {
  4.    int x= 42;
  5.    return 0;
  6. }
  7.  

kind regards,

Jos
Jun 17 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.