Why doesn't this work for a solution?


#1

I was able to correctly write the program using functions, but afterwards started playing around with it to see if I could write it another way.

Could someone explain to me why the following returns errors? Xcode keeps returning “control reaches end of non void function”, but I’m not familiar with that. My assumption was that secondInt would supply the variable 5 to the square function, allowing it to compute the square and then print all of it.

#include <stdio.h>

int square (int root)
{
int newstNum = root;
int newNumber = root * root;

printf("\"%d\" squared is \"%d\".\n", newstNum, newNumber);

}

int main(int argc, const char * argv[])
{
int firstInt = 5;
int secondInt = square (firstInt);

return 0;

}


#2

[quote][code]#include <stdio.h>

int square (int root)
{
int newstNum = root;
int newNumber = root * root;

printf(""%d" squared is “%d”.\n", newstNum, newNumber);

}
[/code][/quote]
The square () function forgot to return the int it promised to return.

Compare:

[code]#include <stdio.h>

int square (int root)
{
int result = root * root;
return result;
}
[/code]
int square (int) means square is a function which expects an input value of type int, and which returns an output value of type int.

So if you do this:

#include <stdio.h>
int square (int root)
{
   int result = root * root;
}

Xcode will be unhappy!

[Become a competent programmer faster than you can imagine: pretty-function.org]