0

When programming functions or checking command line arguments, is it necessary to return always return a value?

For functions that are casted as an int, we must return 0 when the program runs and return 1 or any other number if the program has an error.

What about command line arguments? I was doing pset 2 and had to program argc to only take 2 arguments and argv to be positive. Do I have to put "return 1" at the bottom if the user did not meet the requirements?

1

A function either returns a value (has a return type) or not (its return type is void). A function that has a return type must return a value. A function whose return type is void mustn't return a value.

The main function is a special function. It's the starting point of your program and it returns an int (has a return type of int).

By convention, we return 0 from main upon successful exit or a value that maybe represents an error code otherwise. So, technically, we're NOT restricted to return a specific value from main, but we ARE restricted to return an int value (although even this, the compiler can cover it and return an int value for us).

The value returned from main is useful in a sense that other programs can use it. We often think of the value that's returned from main as the exit status of our program. So, again by convention, when main returns 0, we chose to think of this as a successful termination of the program (no errors).

Since an int value can be any of (2^32 - 1) different values, we have exactly this number of options to return one of them where each one can represent a different status (for example, I may choose to return 1 from main in case the correct number of command-line arguments isn't provided and so on).

For more information about

  1. functions
  2. command-line arguments
1

Functions doesn't really need to return values, you can always set them as void.

The other returns you mention are usually used as exit codes, a 0 means that there was no issue with the program and a 1 that there was.

I.e: User enters 1 argument instead of 2 needed -> shows help -> exits with return 1

That would be for a program that exits if the arguments are not right, if you find that the user didn't provide the needed arguments you can just keep asking for them without returning anything.

Here you have a couple of links that explain functions quite well :)

Hope this helps you!

http://www.tutorialspoint.com/cprogramming/c_functions.htm

http://www.cprogramming.com/tutorial/c/lesson4.html

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .