Z
PRO
last month
Zadecountry asked

Why should a function return int instead of void when it produces a result in C?

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

Hello Zade, really nice question.

The reason the function is defined as int instead of void is that it actually produces a value — the sum. Whenever a function calculates something and you want to use that result later in the program, the function needs a return type that matches the kind of value it gives back. In this case, the sum of natural numbers is an integer, so the function returns an int.

A void function is different. It performs an action but doesn’t hand anything back. For example, a function that only prints something to the screen doesn’t need to return a value, so void makes sense there.

So the rule is simple:
If the function gives back a value, choose a matching return type.
If it doesn’t return anything, use void.

If you have further questions, I'm here to help.

C
This question was asked as part of the Learn C Programming course.