Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Instruct a Function to Exit Early in C Programming

In C programming, the return keyword can blast out of a function at any time, sending execution back to the statement that called the function. Or, in the case of the main() function, return exits the program. That rule holds fast even when return doesn’t pass back a value, which is true for any void function you create. Consider Exiting a Function with return.

EXITING A FUNCTION WITH RETURN

#include <stdio.h>
void limit(int stop);
int main()
{
 int s;
 printf("Enter a stopping value (0-100): ");
 scanf("%d",&s);
 limit(s);
 return(0);
}
void limit(int stop)
{
 int x;
 for(x=0;x<=100;x=x+1)
 {
 printf("%d ",x);
 if(x==stop)
 {
 puts("You won!");
 return;
 }
 }
 puts("I won!");
}

The silly source code shown in Exiting a Function with return calls a function, limit(), with a specific value that's read in Line 10. A loop in that function spews out numbers. If a match is made with the function’s argument, a return statement (refer to Line 25) bails out of the function.

Otherwise, execution continues and the function simply ends. No return function is required at the end of the function because no value is returned.

Exercise 1: Create a new project using the source code shown in Exiting a Function with return. Build and run.

One problem with the code is that it doesn’t check to ensure that only values from 0 to 100 are input.

Exercise 2: Modify the source code from Exiting a Function with return so that a second function, verify(), checks to confirm whether the value input is within the range from 0 to 100. The function should return the constant TRUE (defined as 1) if the value is within the range, or FALSE (defined as 0) if not.

When a value is out of range, the program needs to display an error message.

Of course, you always win after you’ve confined input for Exercise 2 to the given range. Perhaps you can figure out another way to code the limit() function so that the computer has a chance — even if it cheats?

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.