473,657 Members | 2,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.
"Affirmitiv e" 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 30111
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.Button1C lick(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*****@nowher e.uk> wrote in message
news:42******** *******@news.bt click.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.Button1C lick(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********@ntl world-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********@ntl world-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.b orland-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

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

Similar topics

2
2213
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(){} show('delete(f):',delete(f)) ; // false g = function(){} ;
11
2178
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 execute, while the function itself returns true. A var_dump shows that all the variables are valid, and I can run the exact same update query at the mysql command line without errors. I've
4
3009
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 == null ) { return( false ) ;
1
3771
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 minIOPort); bool flag = ThreadPool.SetMinThreads(4, minIOPort); ThreadPool.GetAvailableThreads(out newWorker, out newIOPort); After running this flag is true, but the worker value is still set to 25. I am using .Net 1.1.4322 and this call was...
59
4577
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 So I changed my test for the obvious "if type(v) is bool", but I still find it confusing that "0 in " returns True
12
2663
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 strVar "Bob is from Canada" -- returns false
8
5865
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 checked to make sure that the variables have values and that the proper expire time is set and etc. Any ideas? <?php foreach($_POST as $name => $value){ if($name == 'hItem'){ $item = $value;
9
8434
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 <br>$filename <br>Attempting deletion "; if(unlink($destination.$filename)) $exitmsg .= '<br>Success deleting. Please try again '; else
3
9012
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 = null;
1
1705
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 the values. If it is returns false it should not post back. Please do help me on this.
0
8421
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8325
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8742
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7354
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1734
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.