473,387 Members | 1,398 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

if (-1) returns true

Hi,

I came across this C code which I wanted to understand etc it looked like
this:

if (-1) etc

It made me wonder what the result would be... true or false ?

In C and Delphi

False is defined as zero.
True is defined as non zero.

I find this a bit weird since false and negative and true and positive seem
more intuitive.

Think of a lieutenant who asks a question to a soldier, the soldier will
reply:
"Negative" if it's not true.
"Affirmitive" if it's true.

Therefore wouldn't this be more intuitive ?:

False defined as negative or zero.
True defined as positive.

Bye,
Skybuck.
Nov 14 '05 #1
48 29995
Skybuck Flying wrote:

Therefore wouldn't this be more intuitive ?:

False defined as negative or zero.
True defined as positive.


Where did you learn programming?

--
jc

Remove the -not from email
Nov 14 '05 #2
By the way, negative in this context doesnt mean a number < 0 but
declining.
Nov 14 '05 #3
On Wed, 2 Mar 2005 11:05:56 +0100, "Skybuck Flying"
<no****@hotmail.com> wrote:
Hi,

I came across this C code which I wanted to understand etc it looked like
this:

if (-1) etc

It made me wonder what the result would be... true or false ?

In C and Delphi

False is defined as zero.
True is defined as non zero.


Try this little demo :-

procedure TForm1.Button1Click(Sender: TObject);
begin
Case LongBool( 2 ) Of
True : ShowMessage( 'True' );
False : ShowMessage( 'False' );
Else ShowMessage( 'Oops - Bad LongBool' );
End;

Case Boolean( 2 ) Of
True : ShowMessage( 'True' );
False : ShowMessage( 'False' );
Else ShowMessage( 'Oops - Bad Boolean' );
End;

If LongBool( 2 ) Then
ShowMessage( 'Yet this works for LongBool' );

If Boolean( 2 ) Then
ShowMessage( 'And this works for Boolean' );

ShowMessage( 'Which is why it is very unwise'
+' to EXPLICITLY test for "True"'
+#13'Although, sometimes one does. :-)'
)

end;

Nov 14 '05 #4
The fun thing is that this code is buggy occording to the delphi help:

"
A value of type ByteBool, LongBool, or WordBool is considered True when its
ordinality is nonzero. If such a value appears in a context where a Boolean
is expected, the compiler automatically converts any value of nonzero
ordinality to True.
The previous remarks refer to the ordinality of Boolean values, not to the
values themselves. In Delphi, Boolean expressions cannot be equated with
integers or reals. Hence, if X is an integer variable, the statement

if X then ...;

generates a compilation error. Casting the variable to a Boolean type is
unreliable, but each of the following alternatives will work.
"

Note this part in particular ;): "Casting the variable to a Boolean type is
unreliable"

Bye,
Skybuck.

"J French" <er*****@nowhere.uk> wrote in message
news:42***************@news.btclick.com...
On Wed, 2 Mar 2005 11:05:56 +0100, "Skybuck Flying"
<no****@hotmail.com> wrote:
Hi,

I came across this C code which I wanted to understand etc it looked like
this:

if (-1) etc

It made me wonder what the result would be... true or false ?

In C and Delphi

False is defined as zero.
True is defined as non zero.


Try this little demo :-

procedure TForm1.Button1Click(Sender: TObject);
begin
Case LongBool( 2 ) Of
True : ShowMessage( 'True' );
False : ShowMessage( 'False' );
Else ShowMessage( 'Oops - Bad LongBool' );
End;

Case Boolean( 2 ) Of
True : ShowMessage( 'True' );
False : ShowMessage( 'False' );
Else ShowMessage( 'Oops - Bad Boolean' );
End;

If LongBool( 2 ) Then
ShowMessage( 'Yet this works for LongBool' );

If Boolean( 2 ) Then
ShowMessage( 'And this works for Boolean' );

ShowMessage( 'Which is why it is very unwise'
+' to EXPLICITLY test for "True"'
+#13'Although, sometimes one does. :-)'
)

end;

Nov 14 '05 #5

"Jeremy Collins" <jd********@ntlworld-not.com> wrote in message
news:Xf**************@newsfe3-gui.ntli.net...
Skybuck Flying wrote:

Therefore wouldn't this be more intuitive ?:

False defined as negative or zero.
True defined as positive.


Where did you learn programming?


Behind my computer =D

Fortunately turbo pascal and delphi are great programming languages to learn
to program.

Delphi's help comes to the rescue once again and teaches me how booleans
work:

"
The four predefined Boolean types are Boolean, ByteBool, WordBool, and
LongBool. Boolean is the preferred type. The others exist to provide
compatibility with other languages and operating system libraries.

A Boolean variable occupies one byte of memory, a ByteBool variable also
occupies one byte, a WordBool variable occupies two bytes (one word), and a
LongBool variable occupies four bytes (two words).

Boolean values are denoted by the predefined constants True and False. The
following relationships hold.

Boolean ByteBool, WordBool, LongBool
False < True False <> True
Ord(False) = 0 Ord(False) = 0
Ord(True) = 1 Ord(True) <> 0
Succ(False) = True Succ(False) = True
Pred(True) = False Pred(False) = True
A value of type ByteBool, LongBool, or WordBool is considered True when its
ordinality is nonzero. If such a value appears in a context where a Boolean
is expected, the compiler automatically converts any value of nonzero
ordinality to True.
The previous remarks refer to the ordinality of Boolean values, not to the
values themselves. In Delphi, Boolean expressions cannot be equated with
integers or reals. Hence, if X is an integer variable, the statement

if X then ...;

generates a compilation error. Casting the variable to a Boolean type is
unreliable, but each of the following alternatives will work.

if X <> 0 then ...; { use longer expression that returns Boolean
value }
var OK: Boolean { use Boolean variable }
...
if X <> 0 then OK := True;
if OK then ...;
"

What do they mean with ordinality ?

More text from help files:

"
Ordinal types include integer, character, Boolean, enumerated, and subrange
types. An ordinal type defines an ordered set of values in which each value
except the first has a unique predecessor and each value except the last has
a unique successor. Further, each value has an ordinality which determines
the ordering of the type. In most cases, if a value has ordinality n, its
predecessor has ordinality n - 1 and its successor has ordinality n + 1.

For integer types, the ordinality of a value is the value itself.
Subrange types maintain the ordinalities of their base types.
For other ordinal types, by default the first value has ordinality 0, the
next value has ordinality 1, and so forth. The declaration of an enumerated
type can explicitly override this default.

Several predefined functions operate on ordinal values and type identifiers.
The most important of them are summarized below.

Function Parameter Return value Remarks
Ord ordinal expression ordinality of expression's value Does not take Int64
arguments.
Pred ordinal expression predecessor of expression's value
Succ ordinal expression successor of expression's value
High ordinal type identifier or variable of ordinal type highest value in
type Also operates on short-string types and arrays.
Low ordinal type identifier or variable of ordinal type lowest value in type
Also operates on short-string types and arrays.
For example, High(Byte) returns 255 because the highest value of type Byte
is 255, and Succ(2) returns 3 because 3 is the successor of 2.
The standard procedures Inc and Dec increment and decrement the value of an
ordinal variable. For example, Inc(I) is equivalent to I := Succ(I) and, if
I is an integer variable, to I := I + 1.
"

The order of values ?

Well how I am supposed to know the order of values ?

I can imagine the compiler defining integer values as:

-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 0

or

0 1 2 3 4 5 6 7 8 9 -1 -2 -3 -4 -5 -6 -7 -8 -9

Etc.

Though this is documented above:

"For integer types, the ordinality of a value is the value itself."

What about booleans... well these little functions give it away:

Ord(False) = 0
Ord(True) = 1

Now back to this statement:

"
A value of type ByteBool, LongBool, or WordBool is considered True when its
ordinality is nonzero. If such a value appears in a context where a Boolean
is expected, the compiler automatically converts any value of nonzero
ordinality to True.
The previous remarks refer to the ordinality of Boolean values, not to the
values themselves. In Delphi, Boolean expressions cannot be equated with
integers or reals. Hence, if X is an integer variable, the statement
"

Especially this part:

"the compiler automatically converts any value of nonzero ordinality to
True"

What is therefore the ordinality of -1 ?

Good question eh ? ;)

Apperently ordinality can be negative as well.

Well at least now I understand how delphi defines booleans and false and
true etc.

However I am not a C programmer and I don't care that much about C... it's
just bitching when one has to read C code :D

I have done my part and explained how Delphi works.

Are you good enough to explain how C works ? ;)

Bye,
Skybuck.
Nov 14 '05 #6
Skybuck Flying wrote:
"Jeremy Collins" <jd********@ntlworld-not.com> wrote in message
news:Xf**************@newsfe3-gui.ntli.net...

Skybuck Flying wrote:

Therefore wouldn't this be more intuitive ?:

False defined as negative or zero.
True defined as positive.

Where did you learn programming?


[snip non C exaplanation]

However I am not a C programmer and I don't care that much about C... it's
just bitching when one has to read C code :D

I have done my part and explained how Delphi works.

Are you good enough to explain how C works ? ;)

Bye,
Skybuck.

In Boolean context, a false value is inferred when the expression
compares equal to zero otherwise true.

Krishanu
Nov 14 '05 #7
On Wed, 2 Mar 2005 12:14:23 +0100, "Skybuck Flying"
<no****@hotmail.com> wrote:
The fun thing is that this code is buggy occording to the delphi help:
True
Note this part in particular ;): "Casting the variable to a Boolean type is
unreliable"


Well the problem turns up when the data is read from somewhere else,
say from disk or a stream

Also (and this is the nasty) the return value from some Win APIs

Test this little lulu

If ( Boolean( 2 ) = True ) Then
ShowMessage( 'So True is anything but False' )
Else
ShowMessage( 'An unexpected result' );

On balance I don't think it is much of a problem, once one is aware of
it - but it is useful to know.
Nov 14 '05 #8
Skybuck Flying wrote:
I have done my part and explained how Delphi works.
Uh, thanks.

Are you good enough to explain how C works ? ;)


The same as any other compiled language, when you get down to it.

The point I was hinting at is that you began a rant with some
(probably unknown to you) incorrect assumptions, the most
important of which is the underlying type of your "boolean" value.

It's efficient to fit a "boolean type" into a small space, right?

So why are you assuming a signed type? Why not a byte? What happens
when you assign a negative number to a byte?

Is there a glimmer of light here? Does
FALSE = 0
TRUE = {anything else}
start to make sense?

--
jc

Remove the -not from email
Nov 14 '05 #9
J French wrote:
On Wed, 2 Mar 2005 12:14:23 +0100, "Skybuck Flying"
<no****@hotmail.com> wrote:
The fun thing is that this code is buggy occording to the delphi help:


True
Note this part in particular ;): "Casting the variable to a Boolean type is
unreliable"


Well the problem turns up when the data is read from somewhere else,
say from disk or a stream

Also (and this is the nasty) the return value from some Win APIs

Test this little lulu

If ( Boolean( 2 ) = True ) Then
ShowMessage( 'So True is anything but False' )
Else
ShowMessage( 'An unexpected result' );

On balance I don't think it is much of a problem, once one is aware of
it - but it is useful to know.


Could you please keep your discussions of Delphi off comp.lang.c since
even those of us who *do* program in Delphi are not interested in
discussing it here.

I've set follow ups to alt.comp.lang.borland-delphi since there is
nothing about C in this subthread.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #10

"Skybuck Flying" <no****@hotmail.com> wrote in message
news:d0**********@news4.zwoll1.ov.home.nl...
Hi,

I came across this C code which I wanted to understand etc it looked like
this:

if (-1) etc

It made me wonder what the result would be... true or false ?

In C and Delphi

False is defined as zero.
True is defined as non zero.

I find this a bit weird since false and negative and true and positive
seem
more intuitive.

Think of a lieutenant who asks a question to a soldier, the soldier will
reply:
"Negative" if it's not true.
"Affirmitive" if it's true.

Therefore wouldn't this be more intuitive ?:

False defined as negative or zero.
True defined as positive.

Bye,
Skybuck.


LOL! I like that "Negative" for false the soldier uses...
However incorrect it may be.

I usually use just 1 or 0 for true or false, 0 being false.

Other folks, wiser than I (at least until I learned the trick), used
!0 as an expression for true.

I like the logic of it. We can pretty much agree that 0
is going to be false (not to be confused with success/failure,
which is a different story altogether).

if 0 is false, then the logical complement, !0 will be true.

(but in a success/failure calling sequence, 0 usually
indicates success, and nonzero failure, the value representing
the error coded reason for failure.)

Rufus

Nov 14 '05 #11

"Skybuck Flying" <no****@hotmail.com> wrote in message
news:d0**********@news4.zwoll1.ov.home.nl...
Therefore wouldn't this be more intuitive ?:


Intuition is the application of the cumulative effect of knowledge and
experience. What is intuitive to one person may be counter-intuitive to
another. Unless all participants posses similar knowledge and experience
(including cultural experience) one should never deem something to be
intuitive to the group.

Regardless. Formal languages are defined and it is far better to consult a
language definition than to rely on one's intuition.

Pascal defines type Boolean as possessing two possible values True and False
such that False < True. Delphi preserves this definition.

-1 is a particular visualization of a bit pattern. The same bit pattern can
be visualized as 4294967296, as True, and as 4 characters (the specifics of
which depend on collating sequence). While one person may "intuitively" view
all bit patterns as 4 byte integers, many others don't.

Nov 14 '05 #12
Bruce Roberts wrote:
"Skybuck Flying" <no****@hotmail.com> wrote in message
.... snip ...
Regardless. Formal languages are defined and it is far better to
consult a language definition than to rely on one's intuition.

Pascal defines type Boolean as possessing two possible values True
and False such that False < True. Delphi preserves this definition.
Pascal defines an enumeration: boolean = (false, true). This
means that ord(true) is 1 and ord(false) is zero. Also that true >
false. For Pascal this makes the least significant bit the crucial
one for logical decisions. C, on the other hand, lumps all
non-zero values into the category 'true'.
From ISO10206:


c) Boolean-type. The required type-identifier Boolean shall
denote
the Boolean-type. The Boolean-type shall be an ordinal-type.
The values shall be the enumeration of truth values denoted by
the required constant-identifiers false and true, such that
false is the predecessor of true. The ordinal numbers of the
truth values denoted by false and true shall be the integer
values 0 and 1 respectively.

Note that boolean is not a reserved word, but a pre-defined type.
As such it can be user redefined.

OT for c.l.c. F'ups set.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #13
In C boolean operators are defined to return 0 or 1,
because you can assign this value to ordinals of any bit width,
whether signed or not.

The if statement regards any non-zero value as true.
You can easily understand this,
if you search for similar behaviour of
bool, bit-fields and sets.
If you use an ordinal as bit-field,
which also represents a set,
you can test, if the set is non-empty.
The result is true on any non-zero bit in the field.
This is any non-zero ordinal value.
Nov 14 '05 #14
On Wed, 2 Mar 2005 11:05:56 +0100, "Skybuck Flying"
<no****@hotmail.com> wrote:
I find this a bit weird since false and negative and true and positive seem
more intuitive.
Ah, but signed or unsigned? If you're going to interpret booleans as a
numeric quantity, then what sort of numeric quantity makes sense?

If you actually want the interpretation you have, then before doing
the IF test, simply invert the bits and AND with 0x80000000.
Think of a lieutenant who asks a question to a soldier, the soldier will
reply: Therefore wouldn't this be more intuitive ?:


Maybe, but not when you think in terms of bits. The zero flag is
maintained on many processors throughout most operations and is quick
and easy to check (and to calculate).

MH.
Nov 14 '05 #15
Jeremy Collins <jd********@ntlworld-not.com> wrote:
Skybuck Flying wrote:

Therefore wouldn't this be more intuitive ?:

False defined as negative or zero.
True defined as positive.


Where did you learn programming?


The same place he learned when not to cross-post uselessly: nowhere.

Richard
Nov 14 '05 #16
"Skybuck Flying" <no****@hotmail.com> wrote in message
news:d0**********@news4.zwoll1.ov.home.nl...
In C and Delphi

False is defined as zero.
True is defined as non zero.

I find this a bit weird since false and negative and true and positive seem more intuitive.


CPUs in the real world have very efficient instructions for setting and
testing zero vs. nonzero, so it makes sense for C to take advantage of that.

If you were to use negative vs positive, the test degenerates to looking at
whether the sign bit is zero or nonzero anyways. That method also requires
that all boolean variables are signed, whereas the C method works equally
well with signed and unsigned variables.

S

--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin

Nov 14 '05 #17
Skybuck Flying wrote:

Therefore wouldn't this be more intuitive ?:

False defined as negative or zero.
True defined as positive.


#include <stdio.h>

int main(void)
{
unsigned int i;

if (i = -1)
printf("Always true\n");
else
printf("Buy a new computer\n");

return 0;
}
Nov 14 '05 #18
On Fri, 4 Mar 2005 13:48:14 -0600, "Stephen Sprunk"
<st*****@sprunk.org> wrote:

<snip>
If you were to use negative vs positive, the test degenerates to looking at
whether the sign bit is zero or nonzero anyways. That method also requires
that all boolean variables are signed, whereas the C method works equally
well with signed and unsigned variables.


Have you ever done any Assembler ?

Amazing the crap people come up with nowadays
- it reminds me of yesterday

Sprunk - you are talking out of your fundamental oriffice

And, Sprunk, now I am drunk - but tomorrow I might be sober
- as for you understanding the crud you are spouting
- chances are zilch

You annoyed me, and I'm pretty sure that you cannot work out why.

Nov 14 '05 #19
"J French" <er*****@nowhere.uk> wrote in message
news:42****************@news.btclick.com...
On Fri, 4 Mar 2005 13:48:14 -0600, "Stephen Sprunk"
<st*****@sprunk.org> wrote:

<snip>
If you were to use negative vs positive, the test degenerates to looking atwhether the sign bit is zero or nonzero anyways. That method also requiresthat all boolean variables are signed, whereas the C method works equally
well with signed and unsigned variables.
Have you ever done any Assembler ?


Yes, quite a bit.
Amazing the crap people come up with nowadays
- it reminds me of yesterday

Sprunk - you are talking out of your fundamental oriffice

And, Sprunk, now I am drunk - but tomorrow I might be sober
- as for you understanding the crud you are spouting
- chances are zilch
Instead of ad hominem attacks, why don't you point out where I said
something wrong? Perhaps in your admitted drunkenness you failed to
understand something.
You annoyed me, and I'm pretty sure that you cannot work out why.


I have no clue.

S

--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin

Nov 14 '05 #20
Skybuck Flying wrote:
Hi,

I came across this C code which I wanted to understand etc it looked like
this:
if (-1) etc


You perhaps weren't aware that -1 has been the "value" of true since the
earliest microprocessor days, and even before that? Why? Because in
two's complement math, a 16 bit integer $FFFF (all bits on) is equal to
1. Now do you get it?

Warren
Nov 14 '05 #21
> I find this a bit weird since false and negative and true and positive seem
more intuitive.


Weird only because you aren't aware of the underlying way in which CPUs
operate. Anthropomorphizing your machine isn't all that helpful in this
case.

CPUs typically can do an operation on an entire register in the same
number of clock cycles as they can do an operation on a single bit. That
being so, even though you can think of True and False being bit-sized
constants in your mind, they are in fact typically compiler-builtin
constants defined to be the values used by your microprocessor.

And since -1 has been the most commonly used "value" for the boolean
True state since the earliest microprocessor days, and even before that,
it makes sense that in both C, and Pascal, and other languages,
including the Commodore 64's BASIC interpreter, and most other
Microsoft-derived BASICs, true is also -1.

In two's complement math, a 16 bit integer $FFFF (all bits on) is equal
to -1. In CPUs with 32 bit registers, the DWORD/Cardinal/Longint value
$FFFFFFFF is also the internal way in which -1 is represented in
twos-complement form.
Regards,

Warren

Nov 14 '05 #22
Warren Postma <wp@tekran.spammenziemichnichtdankeschon.com> writes:
You perhaps weren't aware that -1 has been the "value" of true since
the earliest microprocessor days, and even before that?


In C, 1 is the value of true.

7.16 Boolean type and values <stdbool.h>
1 The header <stdbool.h> defines four macros.
2 The macro
bool
expands to _Bool.
3 The remaining three macros are suitable for use in #if
preprocessing directives. They are

true
which expands to the integer constant 1,
--
Ben Pfaff
email: bl*@cs.stanford.edu
web: http://benpfaff.org
Nov 14 '05 #23

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
In C, 1 is the value of true.


I've never had a terribly strong grasp of C, but IIRC, C doesn't have an
intrisic type Boolean. In fact I had quite a shock moving from ALGOL type
languages to C, in part, because of this.
Nov 14 '05 #24

Ben Pfaff wrote:
Warren Postma <wp@tekran.spammenziemichnichtdankeschon.com> writes:

You perhaps weren't aware that -1 has been the "value" of true since
the earliest microprocessor days, and even before that?

In C, 1 is the value of true.

7.16 Boolean type and values <stdbool.h>
1 The header <stdbool.h> defines four macros.
2 The macro
bool
expands to _Bool.
3 The remaining three macros are suitable for use in #if
preprocessing directives. They are

true
which expands to the integer constant 1,


True enough, but any non-null is considered true, if any bits are
set, it is true, all bits must be 0 to be considered false.

Nov 14 '05 #25


Bruce Roberts wrote:
In C, 1 is the value of true.

I've never had a terribly strong grasp of C, but IIRC, C doesn't have an
intrisic type Boolean. In fact I had quite a shock moving from ALGOL type
languages to C, in part, because of this.


I love that about C, you can test any variable as if it were a boolean.

if(somechar){
// Do your thing
}

or

if(somebyte){
// Ditto
}

Nov 14 '05 #26
Bruce Roberts wrote:
"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
In C, 1 is the value of true.


I've never had a terribly strong grasp of C, but IIRC, C doesn't have an
intrisic type Boolean. In fact I had quite a shock moving from ALGOL type
languages to C, in part, because of this.


C99 introduces the type _Bool which can take the values 0 and 1.
If you #include <stdbool.h>, you get bool, false and true.

Apart from that: Even though everything !=0 is considered true,
"A && B" gives you 1 if both A and B are true.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #27

"Warren Postma" <wp@tekran.spammenziemichnichtdankeschon.com> wrote in
message news:26*******************@news20.bellglobal.com.. .
And since -1 has been the most commonly used "value" for the boolean
True state since the earliest microprocessor days, and even before that,
it makes sense that in both C, and Pascal, and other languages,
including the Commodore 64's BASIC interpreter, and most other
Microsoft-derived BASICs, true is also -1.


What is common to you is not to me. First, -1 is a number, not a Boolean
value. Second, -1 is a number, not a binary value. In fact -1 has many
different binary representations. There is True and False in type Boolean.
Why should anyone care or try to depend on how a compiler actually
implements this. Finally, in my admittedly limited experience with
microprocessor assembly languages its much more common to see instructions
like JZ and JNZ than J-1 and JNOT-1.

Original Pascal, BTW, defined True to be > False. A property that holds true
today in any variant of Pascal with which I'm familiar. Original C doesn't
even have a Boolean type and the fact that one can find different values for
True in existing published libraries says to me that there is still debate
in that community over an appropriate value for True.
Nov 14 '05 #28
In comp.lang.c ATM Dude <ne**@phreakshow.no> wrote:

(groups trimmed to clc)
True enough, but any non-null is considered true, if any bits are
set, it is true, all bits must be 0 to be considered false.


That's incorrect; an implementation may use any bit pattern internally
to represent a null pointer.

http://www.eskimo.com/~scs/C-faq/q5.13.html

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #29
"Bruce Roberts" <be*@bounceitattcanada.xnet> writes:
I've never had a terribly strong grasp of C, but IIRC, C doesn't have an
intrisic type Boolean.


C99 has intrinsic type _Bool, which represents only 0 and 1.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #30
In article <dW*******************@news20.bellglobal.com>,
Bruce Roberts <be*@bounceitattcanada.xnet> wrote:
:Original C doesn't
:even have a Boolean type and the fact that one can find different values for
:True in existing published libraries says to me that there is still debate
:in that community over an appropriate value for True.

Not to me. To me it means that an implimenter that wants to
construct a 'True' in C is free to choose from a large number of
values, but must choose *one* of those values. Which of them
doesn't matter. Any non-zero value is "appropriate" for True in C.

What were you expecting, that the implimenters would code
isTrue(value) as

value == -1 || value == -2 || value == -3 || value == -4 ... ||
value == 1 || value == 2 || value == 3 || value == 4 ...

listing all possible values that are considered "true" in C?
:Original Pascal, BTW, defined True to be > False. A property that holds true
:today in any variant of Pascal with which I'm familiar.

You probably aren't aware, then, that the original Pascal's API
for interfacing to libraries defined true as "all bits set".
It usually caused extra work for the compilers, but twas how it was
defined. Comparisons would be made unsigned, but signed moves
(with sign extension) would be used when punting a boolean up to
a wider type.

Pascal may have hid the dirt under the covers, but only for that
limited set of functions that Pascal was usable for. As soon as
you tried to write libraries to impliment Pascal or needed to
interface to something platform dependant, you had to know the details.
I worked on a large device control project that was implimented in
Pascal -- we had to bash all kinds of extensions in to make Pascal
useable for anything other than instructional purposes. [That's why
Wirth went ahead and wrote Modula2 -- because Pascal was not suitable
for real software engineering.]
--
Entropy is the logarithm of probability -- Boltzmann
Nov 14 '05 #31
On Mon, 7 Mar 2005 13:17:23 -0500, "Bruce Roberts"
<be*@bounceitattcanada.xnet> wrote:
Original Pascal, BTW, defined True to be > False. A property that holds true
today in any variant of Pascal with which I'm familiar.


In addition, depending on exactly *which* definition of Pascal you
want to be bound by:

True = Succ(False)
Ord(False) = 0

Thinking of C style booleans, It seems to me that a dedicated boolean
type is nice, if only because it stops student programmers doing silly
things like:

if (some_var == TRUE)

or (even worse)

if (some_var == TRUE)
some_other_var = FALSE;
else
some_other_var = TRUE;

A coding style which I consider shows at best a poor appreciation of
the expressiveness of the language, and at worst a flagrant disregard
for the actual rules of the language leading to bugs.

One of the things I prefer about Object Pascal, is that given the
design philosophy, it's possible to write thousands of lines of code
without a single numberic constant.

Having said that, when it comes to device drivers, I'll stick to C :-)

MH.
Nov 14 '05 #32

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
C99 has intrinsic type _Bool, which represents only 0 and 1.


Not according to Michael Mair. His post indicates that <stdbool.h> has to be
included. Presumably there is only one <stdbool.h> ;).
Nov 14 '05 #33
Bruce Roberts wrote:

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
C99 has intrinsic type _Bool, which represents only 0 and 1.


Not according to Michael Mair. His post indicates that <stdbool.h> has to be
included. Presumably there is only one <stdbool.h> ;).


Read Mr Mair's reply more carefully.
Nov 14 '05 #34

"Walter Roberson" <ro******@ibd.nrc-cnrc.gc.ca> wrote in message
news:d0**********@canopus.cc.umanitoba.ca...
What were you expecting, that the implimenters would code
isTrue(value) as

value == -1 || value == -2 || value == -3 || value == -4 ... ||
I don't care how implementers implement a fundamental type except as it may
impact resource requirements. Why should I have to care? True is True, False
is False as far as I'm concerned those are the only two values that matter
in type Boolean. If the implementers want to implement the type as a
1024-bit value what difference does it make to me as a programmer? None,
except as previously noted.

True is not -1, 0, or 1. True is a bit pattern. -1 is, as I have previously
pointed out, an ambiguous representation of a bit pattern. Are you talking
about signed 8, 16, 32, 48, 64, or 128 bit integers? Are you talking about
sign-bit, one's complement, or two's complement integers? Perhaps -1 is
actually a floating or fixed point value?
You probably aren't aware, then, that the original Pascal's API
for interfacing to libraries defined true as "all bits set".
What "original Pascal API"?
Pascal may have hid the dirt under the covers, but only for that
limited set of functions that Pascal was usable for. As soon as
you tried to write libraries to impliment Pascal or needed to
interface to something platform dependant, you had to know the details.
I worked on a large device control project that was implimented in
Pascal -- we had to bash all kinds of extensions in to make Pascal
useable for anything other than instructional purposes. [That's why
Wirth went ahead and wrote Modula2 -- because Pascal was not suitable
for real software engineering.]


Wirth wrote Modula2, Borland wrote TurboPascal. I still think TP 1-5 are
perhaps the finest compilers around. Certainly the language (TP) was more
than adequate for any software engineering job doable on machines on which
it ran.
Nov 14 '05 #35
"Bruce Roberts" <be*@bounceitattcanada.xnet> writes:
"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
C99 has intrinsic type _Bool, which represents only 0 and 1.


Not according to Michael Mair. His post indicates that <stdbool.h> has to be
included. Presumably there is only one <stdbool.h> ;).


The type _Bool is intrinsic (_Bool is a reserved word).

Including <stdbool.h> gets you an alias "bool" for the type "_Bool",
and the constants "false" and "true". (It was done this way to avoid
breaking pre-C99 programs that define "bool", "false", and "true"
themselves.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #36
Walter Roberson wrote:
.... snip ...
You probably aren't aware, then, that the original Pascal's API
for interfacing to libraries defined true as "all bits set".
It usually caused extra work for the compilers, but twas how it
was defined. Comparisons would be made unsigned, but signed
moves (with sign extension) would be used when punting a
boolean up to a wider type.


Especially since this is way OT for c.l.c, this gross error needs
correction. Pascal always defined booleans as the enumeration
false, true. Check Jensen & Wirths "Pascal Report and User Manual"
if you don't believe me.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #37
Yeah actually true, false was used by Hardware developers, and then came C.

You'll find that 0000 is false and any positive # of bits set is True. It
was true then, and its true now.
"Bruce Roberts" <be*@bounceitattcanada.xnet> wrote in message
news:sH*******************@news20.bellglobal.com.. .

"Walter Roberson" <ro******@ibd.nrc-cnrc.gc.ca> wrote in message
news:d0**********@canopus.cc.umanitoba.ca...
What were you expecting, that the implimenters would code
isTrue(value) as

value == -1 || value == -2 || value == -3 || value == -4 ... ||


I don't care how implementers implement a fundamental type except as it
may
impact resource requirements. Why should I have to care? True is True,
False
is False as far as I'm concerned those are the only two values that matter
in type Boolean. If the implementers want to implement the type as a
1024-bit value what difference does it make to me as a programmer? None,
except as previously noted.

True is not -1, 0, or 1. True is a bit pattern. -1 is, as I have
previously
pointed out, an ambiguous representation of a bit pattern. Are you talking
about signed 8, 16, 32, 48, 64, or 128 bit integers? Are you talking about
sign-bit, one's complement, or two's complement integers? Perhaps -1 is
actually a floating or fixed point value?
You probably aren't aware, then, that the original Pascal's API
for interfacing to libraries defined true as "all bits set".


What "original Pascal API"?
Pascal may have hid the dirt under the covers, but only for that
limited set of functions that Pascal was usable for. As soon as
you tried to write libraries to impliment Pascal or needed to
interface to something platform dependant, you had to know the details.
I worked on a large device control project that was implimented in
Pascal -- we had to bash all kinds of extensions in to make Pascal
useable for anything other than instructional purposes. [That's why
Wirth went ahead and wrote Modula2 -- because Pascal was not suitable
for real software engineering.]


Wirth wrote Modula2, Borland wrote TurboPascal. I still think TP 1-5 are
perhaps the finest compilers around. Certainly the language (TP) was more
than adequate for any software engineering job doable on machines on which
it ran.

Nov 14 '05 #38
CBFalconer <cb********@yahoo.com> wrote in news:422D2283.64B85554
@yahoo.com:
Especially since this is way OT for c.l.c, this gross error needs
correction. Pascal always defined booleans as the enumeration
false, true. Check Jensen & Wirths "Pascal Report and User Manual"
if you don't believe me.


You might also want to check to see what the compiler actually does. The
(D5 Pro UP1) compiler produces two different output depending on the check
of true is being done.

If you have this kind of comparision happening:

if SomeFunction() = true then
begin
end;

then the compiler will test to see if the result from SomeFunction() is
equal to 1 ($[00]01).

However, if you have this kind of comparision happening:

if SomeFunction() then
begin
end;

then the compiler will test to see if the result from SomeFunction() is not
zero!
Cheers,
Nick
Nov 14 '05 #39
infobahn wrote:
Bruce Roberts wrote:
"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...

C99 has intrinsic type _Bool, which represents only 0 and 1.
Not according to Michael Mair. His post indicates that <stdbool.h> has to be
included. Presumably there is only one <stdbool.h> ;).


Nope. It has to be included in order to get "bool", "false" and "true",
respectively; which was what I wanted to indicate. The two sentences
still(*) seem to me not to leave room for other interpretations:

,-
| C99 introduces the type _Bool which can take the values 0 and 1.
| If you #include <stdbool.h>, you get bool, false and true.
`-

Read Mr Mair's reply more carefully.


Thanks -- at least someone understands my ramblings :-)
Cheers
Michael

________
(*) Sometimes I come back and reality did not accommodate itself
in order to fit together with my message; sometimes my language
skills are sufficient to give a wrong enough impression to make
someone correct me.
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #40
Nicholas Ring wrote:
CBFalconer <cb********@yahoo.com> wrote
Especially since this is way OT for c.l.c, this gross error needs
correction. Pascal always defined booleans as the enumeration
false, true. Check Jensen & Wirths "Pascal Report and User Manual"
if you don't believe me.


You might also want to check to see what the compiler actually does.
The (D5 Pro UP1) compiler produces two different output depending on
the check of true is being done.

If you have this kind of comparision happening:

if SomeFunction() = true then
begin
end;

then the compiler will test to see if the result from SomeFunction()
is equal to 1 ($[00]01).

However, if you have this kind of comparision happening:

if SomeFunction() then
begin
end;

then the compiler will test to see if the result from SomeFunction()
is not zero!


If SomeFunction does not return a boolean (see 1st para. above) you
should have a syntax error, and the thing just doesn't compile. I
can't speak for compilers that don't implement Pascal. If you want
to test something for non-zero all you have to do is say so:

IF junkfunction <> 0 THEN ...

This is way OT for c.l.c, so I am setting f'ups. I won't see any
reply. BTW, Delphi does not implement Pascal. At least these days
they have the grace not to claim it does. Pascal has an ISO
standard.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #41
ATM Dude <ne**@phreakshow.no> wrote:
Bruce Roberts wrote:
I've never had a terribly strong grasp of C, but IIRC, C doesn't have an
intrisic type Boolean.


I love that about C, you can test any variable as if it were a boolean.


Well... any _scalar_ type. You can't do this with structs and unions,
and while you can try it with arrays, it's a bit senseless to write a
test that will, because of a quirk in C's array handling, always
evaluate to true.

Richard
Nov 14 '05 #42
"Bruce Roberts" <be*@bounceitattcanada.xnet> wrote:
"Warren Postma" <wp@tekran.spammenziemichnichtdankeschon.com> wrote in
message news:26*******************@news20.bellglobal.com.. .
And since -1 has been the most commonly used "value" for the boolean
True state since the earliest microprocessor days, and even before that,
it makes sense that in both C,
Original C doesn't
even have a Boolean type and the fact that one can find different values for
True in existing published libraries says to me that there is still debate
in that community over an appropriate value for True.


You're both wrong about C. In a context where a boolean value is
required, any non-zero scalar will be taken as true. In a context where
a boolean value results, true will be returned as an int with value 1.
Thus, for example, 4.0 && !NULL equals 1. Any library which doesn't cope
with this doesn't cope well with ISO Standard C, or with any variation
thereon that I've ever used.
Note that in C99, which has a _Bool type built in, and a <stdbool.h>
header which defines boolean, false and true if you want them; true is
an integer 1.

Richard
Nov 14 '05 #43
On Mon, 7 Mar 2005 18:28:45 -0500, in comp.lang.c , "Bruce Roberts"
<be*@bounceitattcanada.xnet> wrote:

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
C99 has intrinsic type _Bool, which represents only 0 and 1.


Not according to Michael Mair. His post indicates that <stdbool.h> has to be
included. Presumably there is only one <stdbool.h> ;).


I didn't see michael's post, but you do not need to include stdbool.h to
get _Bool since its an intrinsic type.

The header defines an macro bool which expands to _Bool, and two macros
true and false which expand to 1 and 0 respectively.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #44
ATM Dude wrote:


Bruce Roberts wrote:
In C, 1 is the value of true.


I've never had a terribly strong grasp of C, but IIRC, C doesn't have an
intrisic type Boolean. In fact I had quite a shock moving from ALGOL type
languages to C, in part, because of this.


I love that about C, you can test any variable as if it were a boolean.

if(somechar){
// Do your thing
}

or

if(somebyte){
// Ditto
}

also with delphi with a little help.
if LongBool(Integervalue) then...

Nov 14 '05 #45
In article <42***************@yahoo.com>,
CBFalconer <cb********@worldnet.att.net> wrote:
:Pascal always defined booleans as the enumeration
:false, true.

Pascal enumerations formed their own type, and the values need
not be sequential as long as the ord() function knows the mapping.
--
Feep if you love VT-52's.
Nov 14 '05 #46
Walter Roberson wrote:
CBFalconer <cb********@worldnet.att.net> wrote:
Pascal always defined booleans as the enumeration false, true.


Pascal enumerations formed their own type, and the values need
not be sequential as long as the ord() function knows the mapping.


It's still OT on c.l.c. F'ups set.

Pascal enumerations have no specific value. However the ord
function can reveal their place in the enumeration, and the succ
and pred functions can select adjacent values. The enumeration is
a grown up independant type in its own right, unlike the C flavor.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #47
"Skybuck Flying" <no****@hotmail.com> wrote in message news:<d0**********@news4.zwoll1.ov.home.nl>...
Hi,

I came across this C code which I wanted to understand etc it looked like
this:

if (-1) etc

It made me wonder what the result would be... true or false ?

In C and Delphi

False is defined as zero.
True is defined as non zero.

I find this a bit weird since false and negative and true and positive seem
more intuitive.

Think of a lieutenant who asks a question to a soldier, the soldier will
reply:
"Negative" if it's not true.
"Affirmitive" if it's true.

Therefore wouldn't this be more intuitive ?:

A Boolean is defined as a "byte" which is unsigned. -1 is 255,
positive, TRUE (or rather, non-false).
False defined as negative or zero.
True defined as positive.


You can do that if you want, wont make a difference for unsigned
integers anyway :)
Nov 14 '05 #48
ni*@aub.dk (Nicolai Hansen) writes:
[...]
A Boolean is defined as a "byte" which is unsigned. -1 is 255,
positive, TRUE (or rather, non-false).


Keep in mind that this is (inappropriately) cross-posted to
alt.comp.lang.borland-delphi and comp.lang.c. I presume your
description applies to Delphi; it's inaccurate for C.

Followups redirected. (My news server doesn't seem to carry
alt.comp.lang.borland-delphi, so I probably won't see any followups.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #49

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: vakap | last post by:
function show() { var s = '' ; for (var i = 0; i<arguments.length; s += '\n'+arguments) ; typeof(window) != 'undefined' ? window.alert(s) : WScript.Echo(s) ; } function f(){}...
11
by: John Moore | last post by:
Hi, I must be missing something obvious. I cannot get this function to run the update query on Line 6, although the call to run the query evaluates true, and both update_cat_total functions...
4
by: Sly | last post by:
Hi! I am facing an unbreakable wall. I have a class 'x' with one array in it called arr; in Equals(x arg) routine I compare the elements of the array. But first I check whether if( arg.arr ==...
1
by: Tim Begin | last post by:
I am attempting to use the ThreadPool.SetMinThreads method as shown in the MSDN example code: int minWorker, minIOPort; int newWorker,newIOPort; ThreadPool.GetAvailableThreads(out minWorker, out...
59
by: Pierre Quentel | last post by:
Hi all, In some program I was testing if a variable was a boolean, with this test : if v in My script didn't work in some cases and I eventually found that for v = 0 the test returned True ...
12
by: ross.oneill | last post by:
Hi, Is there any function in php that will match a word exactly and if it finds it, it returns true. For example if I search for "CA" strVar = "Bob is from Los Angeles CA" - return true ...
8
by: SupraFast | last post by:
I have two hosting accounts. On one, my setcookie script works fine; cookies are created. On the other, the same script doesn't work. The function returns TRUE, but no cookies is created. I...
9
code green
by: code green | last post by:
I have this piece of code to tidy up after a function that calls move_uploaded_file() if(file_exists($destination.$filename)) { $exitmsg .= "<br>File still in temporary location...
3
by: jwdvorak | last post by:
In the following method: public boolean isMemberAlive(String userSsn) throws SQLException { boolean isMemberAlive = false; Connection c = null; Statement s = null; ResultSet rs =...
1
by: muthukumaran08 | last post by:
I have textboxes and dropdownlist on my page. And i have image button when i click this image button i m validating textboxes on javascript and if it returns true, i need to do a post back to save...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.