I wanted to make sure I understand main and function - please correct me if I am misunderstanding them.
The function contains the code that should be executed and main contains the information passed when calling the function?
I don’t think I’m necessarily understanding this correctly but since main is called first no matter what, would it contain whatever’s necessary to ‘initialize’ the following function(s)?
Every executable Objective-C program has a function named main, called by the OS when the program starts.
The main function can contain the entire code or it can call other functions to do the job that is required.
Here are two examples.
The main function does it all.
#import
#import
int main (int argc, const char * argv[])
{
// Print the sum of numbers from 0 to N
//
const unsigned long N = 1024;
unsigned long sum = 0;
for (unsigned long x = 0; x <= N; ++x) {
sum += x;
}
assert (sum == (N * (N+1) / 2));
printf ("sum [0, %lu] = %lu\n", N, sum);
return 0;
}
The main function is calling a function.
#import
#import
unsigned long sumRange (const unsigned long begin, const unsigned long end);
int main (int argc, const char * argv[])
{
// Print the sum of numbers from 0 to N
//
const unsigned long N = 1024;
// delegate the work
const unsigned long sum = sumRange (0, N);
assert (sum == (N * (N+1) / 2));
printf ("sum [0, %lu] = %lu\n", N, sum);
return 0;
}
unsigned long sumRange (const unsigned long begin, const unsigned long end)
{
unsigned long sum = 0;
for (unsigned long x = begin; x <= end; ++x) {
sum += x;
}
return sum;
}