flightdoc5242
flightdoc5242

Reputation: 35

Pass to Value in C math

I am just learning C. i am working through this problem trying to predict the output:

#include <stdio.h>

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.\n", gNumber );
    return 0;
}

int MultiplyIt( int myVar )
{
    return( myVar * gNumber );
}

so if you run this, the output is 512. i am a bit confused on how the calculation is getting from the initial value of 2, then first time through the 'for' loop it then assigns gNumber = 8. then jumps to 512...

maybe i am missing something easy here, but as i said, i am very new to C and programing in general..

Upvotes: 1

Views: 67

Answers (2)

user3629249
user3629249

Reputation: 16540

given the following instrumented code:

#include <stdio.h>

int gNumber;
int MultiplyIt( int myVar );

int main ( void )
{
    int i;
    gNumber = 2;

    for ( i = 1; i <= 2; i++ )
    {
        gNumber *= MultiplyIt( gNumber );
        printf( "\n%s, gNumber *= MultiplyIt(): %d\n", __func__, gNumber);
    }

    printf( "Final value is %d.\n", gNumber );
    return 0;
}

int MultiplyIt( int myVar )
{
    printf( "\n%s, pasted parameter: %d\n", __func__, myVar);
    printf( "%s, global gNumber:  %d\n", __func__, gNumber);
    return( myVar * gNumber );
}

the output is:

MultiplyIt, pasted parameter: 2
MultiplyIt, global gNumber:  2

main, gNumber *= MultiplyIt(): 8

MultiplyIt, pasted parameter: 8
MultiplyIt, global gNumber:  8

main, gNumber *= MultiplyIt(): 512
Final value is 512.

so the first pass through the for loop is:

2*2*2 = 8

the second pass through the for loop is:

8*8*8 = 512

Upvotes: 0

Andrea Corbellini
Andrea Corbellini

Reputation: 17761

Let's start from here:

gNumber *= MultiplyIt( gNumber );

This line contains a call to MultiplyIt with myVar = gNumber. By looking at the return value of that function, we can say that MultiplyIt( gNumber ) is equivalent to gNumber * gNumber. So the line above is equivalent to this:

gNumber *= gNumber * gNumber;

or also:

gNumber = gNumber * gNumber * gNumber;

In plain words, the body of the for-loop replaces gNumber with its cube.

The loop runs two times, with i going from 0 to 1 (inclusive). gNumber is 2 initially. Putting everything together, here's what the loop is doing:

gNumber = 2 * 2 * 2 = 8;    /* First iteration, i = 1 */
gNumber = 8 * 8 * 8 = 512;  /* Second iteration, i = 2 */

Upvotes: 3

Related Questions