C++ Pointers: Solving "g is not defined" & "return" Meaning

  • Context: C/C++ 
  • Thread starter Thread starter beatlesben
  • Start date Start date
  • Tags Tags
    C++
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 3K views
beatlesben
Messages
4
Reaction score
0
Hello, I'm teaching myself C++. I'm pretty much at level one. Anyway I was trying to make a code, playing with pointers:

#include <iostream>

using namespace std;

int main()
{
int x;
int g;
int *p;
x = 1 + g;
cin>> g;
p = &x;
cin.ignore();
count<< *p <<"\n";
cin.get();
return 1;
}


When I run the code it says that g is not defined, but g is what you have to enter, so I don't understand how to define it.

Also could someone explain "return." I don't understand what the value next to it means.

Thanks,
Remember, this is my second day of learning this...
 
Physics news on Phys.org
beatlesben said:
Hello, I'm teaching myself C++. I'm pretty much at level one. Anyway I was trying to make a code, playing with pointers:

#include <iostream>

using namespace std;

int main()
{
int x;
int g;
int *p;
x = 1 + g;
cin>> g;
p = &x;
cin.ignore();
count<< *p <<"\n";
cin.get();
return 1;
}


When I run the code it says that g is not defined, but g is what you have to enter, so I don't understand how to define it.

Also could someone explain "return." I don't understand what the value next to it means.

Thanks,
Remember, this is my second day of learning this...

Hi Beatlesben,

You've properly declared the variable g as integer, so that's set aside a piece of memory for the variable g. However, you have not specified the value of g until:

cin>> g;

When you get to the line of code that says:

x = 1 + g;

C++ does not have a value for g at this time. To fix this, make sure to put the

cin>> g;

before the:

x = 1 + g;

This way, you'll properly read in the value and place it into the variable g, and then you can use g for any future calculations.


----

As a side note, you're already teaching yourself pointers and address references? You must be a fast learner.
 
You're assigning x to 1 + g before g has been read.

Also return 1 typically means failure while 0 is success. A better approach is to #include <cstdlib> and return EXIT_SUCCESS
 
Last edited:
Thanks for the quick responses.
It worked perfectly!