Pages: [1] 2   Go Down
Author Topic: Best coding practice.  (Read 5215 times)
0 Members and 1 Guest are viewing this topic.
Scunthorpe, UK
Offline Offline
Full Member
***
Karma: 0
Posts: 129
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I have seen (none boolean declared) functions that have

return 1;
or
return true;

return 0;
or
return false;

if(i == 0)
or
if(!i)

i know they do just the same thing but was wondering if it's best practice in C++ to do one or the other or is it just personal preferance.
Logged

Offline Offline
Edison Member
*
Karma: 26
Posts: 1339
You do some programming to solve a problem, and some to solve it in a particular language. (CC2)
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Those two constants are not a C++ keyword, but were added to Arduino a while ago:

http://arduino.cc/forum/index.php/topic,46106.0.html

IMHO the best thing to do is use named constants instead of numerical values whenever possible (cfr. Code Complete 2).
Logged

Offline Offline
Edison Member
*
Karma: 19
Posts: 1041
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Those two constants are not a C++ keyword, but were added to Arduino a while ago:

http://arduino.cc/forum/index.php/topic,46106.0.html

No, that's false. The linked thread only discusses that they should be highlighted in the IDE.

I looked here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3376.pdf
on section 2.12

---

I'd say use true/false if you are returning a boolean, and use 0/1 if you are returning a number. Same for the testing --- use ! if it's a bool, ==0 if it's an int.
Logged

Offline Offline
Edison Member
*
Karma: 26
Posts: 1339
You do some programming to solve a problem, and some to solve it in a particular language. (CC2)
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Whoops, I stand corrected :-P

Good suggestion about the test, too.
Logged

New Hampshire
Offline Offline
God Member
*****
Karma: 17
Posts: 781
There are 10 kinds of people, those who know binary, and those who don't.
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

In C++, int values will be automatically cast to bool values in the following manner:
0 is false.
All other values (whether positive or negative) are true.

Not necessarily the most intuitive conversion of values, so it's often more clear to use a specific comparison operation when using ints in an expression.
Logged


Belgium
Offline Offline
Edison Member
*
Karma: 68
Posts: 1918
Arduino rocks; but with my plugin it can fly rocking the world ;-)
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

In C++, int values will be automatically cast to bool values
You probably mean it correctly but the correct phrasing is
"In C++, the bool type is interchangeable with int values (casts in both direction);
In C, boolean values are int values;
in arduino,  boolean value is a unsigned byte value
in arduino, bool maps to _Bool which is a native GCC type (but I'm not sure what it translates to)"
from the arduino code:
Code:
typedef uint8_t boolean;

from http://en.wikipedia.org/wiki/Boolean_data_type
Quote
Standard C (since C99) and several dialects of C such as and Objective-C provide definitions of a Boolean type as an integer type and macros for "false" and "true" as 0 and 1, respectively. However, the initial standards for the C language (1972) provided no Boolean type, and to this day Boolean values are commonly represented by integers (ints) in C programs. The comparison operators ('>', '==', etc.) are defined to return a signed integer (int) result, either zero (for false) or 1 (for true). The same convention is assumed by the logical operators ('&&', '||', '!', etc.) and condition-testing statements ('if', 'while'). Thus logical values can be stored in integer variables, and used anywhere integers would be valid, including in indexing, arithmetic, parsing, and formatting. This approach ("Boolean values are just integers") has been retained in all later versions of C.

C++ has a separate Boolean data type ('bool'), but with automatic conversions from scalar and pointer values that are very similar to those of C. This approach was adopted also by many later languages, especially by some scripting ones such as AWK and Perl. One problem with this approach is that the tests if(t==TRUE){...} and if(t) are not equivalent. Python has a related situation, where the Boolean type, bool is a subtype of the integer type, int, and Booleans False and True act as 0 and 1, respectively, in arithmetic contexts.

The Pascal language (1978) introduced the concept of programmer-defined enumerated types. A built-in Boolean data type was then provided as a predefined enumerated type with values FALSE and TRUE. By definition, all comparisons, logical operations, and conditional statements applied to and/or yielded Boolean values. Otherwise, the Boolean type had all the facilities which were available for enumerated types in general — such as ordering and use as indices. On the other hand, the conversion between Booleans and integers (or any other types) still required explicit tests or function calls, as in ALGOL 60. This approach ("Boolean is an enumerated type") was adopted by most later languages which had enumerated types, such as Modula, Ada and Haskell.

After enumerated types (enums) were added to the ANSI version of C (1989), many C programmers got used to defining their own Boolean types as such, for readability reasons. However, enumerated types are equivalent to integers according to the language standards; so the effective identity between Booleans and integers is still valid for C programs.
but really this is splitting hairs.
Because there are many flavors (typedef/define/class) and in the end -as we are talking about code compatibility when using arduino- it hardly matters.

As to the original question about coding practice
I prefer
return true/false
to
return 0/1
when defining the method as boolean

but I quite often write
return Value>limit;

my most important coding practice rule is :"if you read this code in lets say 3 months from now; would you still understand what it does?"
If the answer is yes: go for it.

Best regards
Jantje
« Last Edit: September 12, 2012, 06:19:55 pm by Jantje » Logged

Do not PM me a question unless you are prepared to pay for consultancy.
Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -

Offline Offline
Edison Member
*
Karma: 19
Posts: 1041
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


in arduino, bool maps to _Bool which is a native GCC type (but I'm not sure what it translates to)"
from http://en.wikipedia.org/wiki/Boolean_data_type
Quote
Standard C (since C99) and several dialects of C such as and Objective-C provide definitions of a Boolean type as an integer type and macros for "false" and "true" as 0 and 1, respectively. However, the initial standards for the C language (1972) provided no Boolean type, and to this day Boolean values are commonly represented by integers (ints) in C programs. The comparison operators ('>', '==', etc.) are defined to return a signed integer (int) result, either zero (for false) or 1 (for true). The same convention is assumed by the logical operators ('&&', '||', '!', etc.) and condition-testing statements ('if', 'while'). Thus logical values can be stored in integer variables, and used anywhere integers would be valid, including in indexing, arithmetic, parsing, and formatting. This approach ("Boolean values are just integers") has been retained in all later versions of C.

C++ has a separate Boolean data type ('bool'), but with automatic conversions from scalar and pointer values that are very similar to those of C. This approach was adopted also by many later languages, especially by some scripting ones such as AWK and Perl. One problem with this approach is that the tests if(t==TRUE){...} and if(t) are not equivalent. Python has a related situation, where the Boolean type, bool is a subtype of the integer type, int, and Booleans False and True act as 0 and 1, respectively, in arithmetic contexts.

The Pascal language (1978) introduced the concept of programmer-defined enumerated types. A built-in Boolean data type was then provided as a predefined enumerated type with values FALSE and TRUE. By definition, all comparisons, logical operations, and conditional statements applied to and/or yielded Boolean values. Otherwise, the Boolean type had all the facilities which were available for enumerated types in general — such as ordering and use as indices. On the other hand, the conversion between Booleans and integers (or any other types) still required explicit tests or function calls, as in ALGOL 60. This approach ("Boolean is an enumerated type") was adopted by most later languages which had enumerated types, such as Modula, Ada and Haskell.

After enumerated types (enums) were added to the ANSI version of C (1989), many C programmers got used to defining their own Boolean types as such, for readability reasons. However, enumerated types are equivalent to integers according to the language standards; so the effective identity between Booleans and integers is still valid for C programs.

The thing you quoted says that bool is a standard type. Where did you see that bool is typedef'd/mapped to _Bool? Neither _bool or _Bool are mentioned in the arduino libs.
Logged

Belgium
Offline Offline
Edison Member
*
Karma: 68
Posts: 1918
Arduino rocks; but with my plugin it can fly rocking the world ;-)
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

The thing you quoted says that bool is a standard type. Where did you see that bool is typedef'd/mapped to _Bool? Neither _bool or _Bool are mentioned in the arduino libs.
In [your arduino location]\hardware\tools\avr\lib\gcc\avr\4.3.2\include\stdbool.h you will find
Code:
#ifndef __cplusplus

#define bool _Bool
#define true 1
#define false 0

#else /* __cplusplus */

/* Supporting <stdbool.h> in C++ is a GCC extension.  */
#define _Bool bool
#define bool bool
#define false false
#define true true

#endif /* __cplusplus */
Which make it dependent on whether you compile as C++ or C whether it will be _Bool or bool.
I have searched for the definition of _Bool and bool in the GCC documentation and it seemed like an integer to me. But I did not find anything remotely close to a "clear answer".
As I am not using bool but boolean -and as I consider this splitting hairs- I don't really care and I did not put much effort in it as well.

Best regards
Jantje
Logged

Do not PM me a question unless you are prepared to pay for consultancy.
Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -

Offline Offline
Edison Member
*
Karma: 19
Posts: 1041
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

That's not arduino, that's avr-libc.

bool, true, and false are all part of C++, but not part of C, [citation needed] but gcc has extensions to get them to work in C also. It really doesn't matter how it's done in the internal gcc libs, since they're so well integrated with the compiler itself. It's just that you said the arduino files defined them, which is not true.

boolean is completely different and I don't see why anyone would ever use it.
Logged

Scunthorpe, UK
Offline Offline
Full Member
***
Karma: 0
Posts: 129
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Back to my original post lol. So if you declare a function as a boolean then use return true or fales but if you declare the function as an byte, int, long use return 0 or 1?
Logged

Belgium
Offline Offline
Edison Member
*
Karma: 68
Posts: 1918
Arduino rocks; but with my plugin it can fly rocking the world ;-)
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

@Pavilion
I would say it is a bad practice to use int/long as return value if you only have 0 and 1 to return.
Why?
Because you use more memory than needed. Actually you only need one bit. But bits are kind of hard to use so you use the smallest memory part possible being "byte". Which is 8 times more than you actually need. Making it int means 16 times more memory usage than needed, long .....
When programming for PC/MAC/Mainframe nobody will really care nowadays (it used to be different). When programming a PIC it can make a difference.

As I stated several times before :Your question is really splitting hairs. Because technically there is no difference between boolean and byte on the arduino platform. And in the end the code quality is defined by the code behaviour; which by default will be equal using byte/boolean and 0;1/true/false.
The difference is in the mind of the person that reads it. In other words in the maintainability of the code. In our minds there is a difference between 1 and true. You can say "1 volt" but you can not say "true volt". For the arduino that is the same for humans it is not.

Conclusion: If you want to write readable code:
And you want to use the human boolean concept: use boolean/bool; true and false.
And you want to use values: take the smallest (in memory occupation terms) object that fits your needs. 0->255 => byte -32767 -> 32767 => int ..... (don't forget the unsigned and signed options)
Best regards
Jantje

@WizenedEE
bool, true, and false are all part of C++, but not part of C, [citation needed]
I think the text I quoted states that: "bool, true, and false are all part of C++" and "boolean, true, and false are all part of C (since C99)"

It's just that you said the arduino files defined them, which is not true.
Can you please quote my statement that makes you think I said so?

boolean is completely different and I don't see why anyone would ever use it.
Wikipedia states "C++ has a separate Boolean data type ('bool'), but with automatic conversions from scalar and pointer values that are very similar to those of C."
You state "completely different" wikipedia states "very similar". Please take up your concerns with wikipedia so we all can learn?
Wikipedia states "One problem with this approach is that the tests if(t==TRUE){...} and if(t) are not equivalent."
Which I think is a really good reason not to use bool.
Jantje



Logged

Do not PM me a question unless you are prepared to pay for consultancy.
Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -

Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 207
Posts: 12909
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
As I stated several times before :Your question is really splitting hairs. Because technically there is no difference between boolean and byte on the arduino platform.

In some expressions, byte will be promoted to intbool (with true and false) is a better choice.  Using bool when the return value really is a boolean (true/false) value allows the compiler to perform optimizations it would otherwise not be able to perform.
Logged

Belgium
Offline Offline
Edison Member
*
Karma: 68
Posts: 1918
Arduino rocks; but with my plugin it can fly rocking the world ;-)
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

In some expressions, byte will be promoted to intbool (with true and false) is a better choice.  Using bool when the return value really is a boolean (true/false) value allows the compiler to perform optimizations it would otherwise not be able to perform.
Coding Badly
Do you have a link to the promotion to int for byte that does not happen to bool?
Do you have a link that explains the optimizations that can happen?
Best regards
Jantje
Logged

Do not PM me a question unless you are prepared to pay for consultancy.
Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -

Left Coast, CA (USA)
Offline Offline
Brattain Member
*****
Karma: 361
Posts: 17294
Measurement changes behavior
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I had hoped to learn something following this thread, but I am more confused now then before this thread was started.  smiley-confuse

So can someone explain it in simple words that a hardware guy could understand? What must I come away with from this topic that is important to my writing 'better' code in the future? What kind of unintended bugs could I put into my sketch if I misunderstand what is trying to be communicated here. Keep it simple and I've always found example code to be more effective then just English words, these postings will out live us all.

Lefty
« Last Edit: September 14, 2012, 02:41:32 pm by retrolefty » Logged

Offline Offline
Edison Member
*
Karma: 26
Posts: 1339
You do some programming to solve a problem, and some to solve it in a particular language. (CC2)
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code is read more than it's written. So read-time convenience is to be favoured over write-time convenience (not my words, cfr Code Complete 2).
So using boolean and true/false is preferable because it makes the code easier to understand, IMHO.

As always, just my 2 cents.
Logged

Pages: [1] 2   Go Up
Jump to: