Help with understanding Pointers...
Can anyone explain who the answer of 512 was reached for this code?
int gNumber;
int MultiplyIt( int myVar );
int main (int argc, const char * argv[]) {
int i;
gNumber = 2;
for ( i = 1; i <= 2; i++ )
gNumber *= MultiplyIt( gNumber );
printf( "Final value is %d.", gNumber );
return 0;
}
int MultiplyIt( int myVar ) {
return( myVar * gNumber );
}
Barely grasping it but let's see.
As I am trying to learn C from an ebook as a precursor to developing with Objective C I can see that I must have gone over some of the initial basics a little too quickly to not be getting this.
Maybe if I try and explain what my interpretation is someone will spot the gaping whole in my logic. By the way, I'm sure you are all explaining it very well so thanks for all your help so far.
[int gNumber;] prototype definition for the compiler to be prepared for what's coming.
[int MultiplyIt( int myVar );] prototype definition for MultiplyIt with int myVar as a parameter.
[int main (int argc, const char * argv[]) {] the program starts...
[int i;] i is declared
[gNumber = 2; ] the global variable is set with a value of '2'.
[for ( i = 1; i <= 2; i++ )] a counter is initiated starting with a value of 1, it is then checked against the condition to see if it is true, it is still less than 2 so 1 is added to it to make it 2.
Am I right so far? where does it go next?
[gNumber *= MultiplyIt( gNumber );]
printf( "Final value is %d.", gNumber );
return 0;
}
int MultiplyIt( int myVar ) {
return( myVar * gNumber );
}