Go Down

Topic: When to use int and when to use void when creating functions?  (Read 78 times) previous topic - next topic

Batool_Khader

When do we use int and when do use void when creating and defining functions? I assume that it has to do with the function itself and what it returns, so for example when the function returns numbers then it'll be defined with an integer, and when it has conditional statements, processes and returns nothing, then we use void. Is this correct?

[int ReadLightSensor(){
x = analogRead(A0);
return (x)}

void BulbControl(){
if (x>=500){
digitalRead (13, HIGH);} ]
Arduino Rocks!!

Whandall

I assume that it has to do with the function itself and what it returns,
so for example when the function returns numbers then it'll be defined with an integer,
and when it has conditional statements, processes and returns nothing, then we use void.
Is this correct?
Somehow.
Forget about the "when it has conditional statements, processes", it's only connected to the return value of the function.

The function type merely describes what the function returns (the value that the function call evaluates to).
If it does not return a value it is declared void.
Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. (D.Adams)

UKHeliBob

The data type in front of a function name indicates which data type it returns, if any.  The data type of void indicates that nothing will be returned and any other data type indicates that the function may return data of that type.  Note that it may not actually return any data, although this would be regarded as bad practice.  

Note too that in order to return data a function must do it explicitly.  Just changing the value of a variable in a function does not cause it to be returned.  If the variable is a global then it does not need to be returned in any case.
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

Go Up