473,747 Members | 2,946 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strange integer-pointer behaviour

I've ran into some fishy code that, at first glance, is buggy, but it
seems to work correctly
and none of the compilers I've tried (five so far, on various systems)
gives any warnings.
The code:
=============== =============
#include <stdio.h>

void
fcn (char *str)
{
if (str == '\0')
{
printf ("str!\n");
}
}

int
main (void)
{
fcn ('\0');
return 0;
}
=============== =============
My understanding so far: '\0' is passed to fcn(), it equals integer 0,
which in turn "equals"
a NULL pointer in terms of zero-ness. The 0 in fcn() is then compared
to '\0' which is also a 0.
No warnings, no errors, code works (or so it seems).
But - if I pass e.g. '\1' to fcn() than all the compilers complain
with similar warnings,
i.e. making a pointer from integer without a cast.

My question is, why don't the compilers complain when '\0' is passed?
Shouldn't they give
the same warning, as it's also an integer (albeit 0 in value)?

--
WYCIWYG - what you C is what you get

Aug 13 '07 #1
17 1863
matevzb wrote On 08/13/07 13:35,:
I've ran into some fishy code that, at first glance, is buggy, but it
seems to work correctly
and none of the compilers I've tried (five so far, on various systems)
gives any warnings.
The code:
=============== =============
#include <stdio.h>

void
fcn (char *str)
{
if (str == '\0')
{
printf ("str!\n");
}
}

int
main (void)
{
fcn ('\0');
return 0;
}
=============== =============
My understanding so far: '\0' is passed to fcn(), it equals integer 0,
which in turn "equals"
a NULL pointer in terms of zero-ness. The 0 in fcn() is then compared
to '\0' which is also a 0.
No warnings, no errors, code works (or so it seems).
But - if I pass e.g. '\1' to fcn() than all the compilers complain
with similar warnings,
i.e. making a pointer from integer without a cast.

My question is, why don't the compilers complain when '\0' is passed?
Shouldn't they give
the same warning, as it's also an integer (albeit 0 in value)?
A literal constant zero[*] used in a pointer context
*is* a null pointer constant. In the code above, '\0'
is just a decorative way to write a literal constant zero.
The compiler sees that it's being used where a pointer is
expected, so the compiler recognizes the zero as a null
pointer constant instead of as an integer. Indeed, you
will find that on many systems the NULL macro is defined
as an unadorned zero.
[*] Any zero-valued constant integer expression will
do; try `fcn (42 / 100)', for example. Also, the
expression is still a null pointer constant if it
is cast to `void*'.

This special treatment applies only to

- Zero-valued expressions: If the expression's value
is non-zero, the expression cannot be a null pointer
constant. That's why the compiler complained when
you tried to use '\1' as an argument to fcn().

- Integer-valued expressions: If the expression's type
is `double' or `float' or `struct fubar', it is not
a null pointer constant. fcn(0.0) won't work.

- Constant expressions: If the expression is not a
compile-time constant, it is not a null pointer
constant. fcn(x - x) won't work; you can deduce
that the argument will always be zero, but from
the compiler's point of view it's just a remarkable
coincidence.

The FAQ has a section devoted to null pointers; you
might find it helpful.

--
Er*********@sun .com
Aug 13 '07 #2
On Aug 13, 7:58 pm, Eric Sosman <Eric.Sos...@su n.comwrote:
A literal constant zero[*] used in a pointer context
*is* a null pointer constant. In the code above, '\0'
is just a decorative way to write a literal constant zero.
The compiler sees that it's being used where a pointer is
expected, so the compiler recognizes the zero as a null
pointer constant instead of as an integer. Indeed, you
will find that on many systems the NULL macro is defined
as an unadorned zero.
Yes, sorry about even posting this. Moments after I posted, I realized
that all bets are off with 0 with regards to (pointer) type
checking...
Thanks

--
WYCIWYG - what you C is what you get

Aug 13 '07 #3
matevzb wrote On 08/13/07 14:30,:
On Aug 13, 7:58 pm, Eric Sosman <Eric.Sos...@su n.comwrote:
> A literal constant zero[*] used in a pointer context
*is* a null pointer constant. In the code above, '\0'
is just a decorative way to write a literal constant zero.
The compiler sees that it's being used where a pointer is
expected, so the compiler recognizes the zero as a null
pointer constant instead of as an integer. Indeed, you
will find that on many systems the NULL macro is defined
as an unadorned zero.

Yes, sorry about even posting this. Moments after I posted, I realized
that all bets are off with 0 with regards to (pointer) type
checking...
Well, no, not exactly. There is no need to type-check
a NULL, because NULL is a perfectly good value for any kind
of pointer at all. The confusion (what remains of it) comes
from the fact that there are many ways to spell NULL.

Gertrude Stein never said "A NULL is a '\0' is a 0,"
but she could have.

--
Er*********@sun .com
Aug 13 '07 #4
Eric Sosman <Er*********@su n.comwrites:
matevzb wrote On 08/13/07 14:30,:
>On Aug 13, 7:58 pm, Eric Sosman <Eric.Sos...@su n.comwrote:
>> A literal constant zero[*] used in a pointer context
*is* a null pointer constant. In the code above, '\0'
is just a decorative way to write a literal constant zero.
The compiler sees that it's being used where a pointer is
expected, so the compiler recognizes the zero as a null
pointer constant instead of as an integer. Indeed, you
will find that on many systems the NULL macro is defined
as an unadorned zero.

Yes, sorry about even posting this. Moments after I posted, I realized
that all bets are off with 0 with regards to (pointer) type
checking...

Well, no, not exactly. There is no need to type-check
a NULL, because NULL is a perfectly good value for any kind
of pointer at all. The confusion (what remains of it) comes
from the fact that there are many ways to spell NULL.

Gertrude Stein never said "A NULL is a '\0' is a 0,"
but she could have.
On the other hand, I'd like my compiler to warn me about using '\0' as
a null pointer constant, at least optionally. It's perfectly legal,
but it usually indicates a conceptual error on the part of the
programmer.

--
Keith Thompson (The_Other_Keit h) 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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 13 '07 #5
Eric Sosman wrote:
matevzb wrote On 08/13/07 14:30,:
Yes, sorry about even posting this. Moments after I posted, I
realized that all bets are off with 0 with regards to (pointer) type
checking...

Well, no, not exactly. There is no need to type-check
a NULL, because NULL is a perfectly good value for any kind
of pointer at all. The confusion (what remains of it) comes
from the fact that there are many ways to spell NULL.

Gertrude Stein never said "A NULL is a '\0' is a 0,"
but she could have.
Well, her code was notoriously buggy anyway.


Brian

Aug 13 '07 #6
- Constant expressions: If the expression is not a
compile-time constant, it is not a null pointer
constant. fcn(x - x) won't work; you can deduce
that the argument will always be zero, but from
the compiler's point of view it's just a remarkable
coincidence.
But I compiled the following code using "gcc -Wall " options.It does
not throw even warning .
#include <stdio.h>

void
fcn (char *str)
{
if (str == NULL)
{
printf ("str!\n");
}

}
int
main (void)
{
int x;
fcn (x - x);
return 0;

}

Aug 14 '07 #7
somenath wrote On 08/14/07 10:26,:
> - Constant expressions: If the expression is not a
compile-time constant, it is not a null pointer
constant. fcn(x - x) won't work; you can deduce
that the argument will always be zero, but from
the compiler's point of view it's just a remarkable
coincidence.


But I compiled the following code using "gcc -Wall " options.It does
not throw even warning .
#include <stdio.h>

void
fcn (char *str)
{
if (str == NULL)
{
printf ("str!\n");
}

}
int
main (void)
{
int x;
fcn (x - x);
return 0;

}
<off-topic>

Try "-Wall -W -O2" or even "-Wall -W -ansi -pedantic -O2".
Despite its inclusive-sounding name, "-Wall" does not enable
all of the warnings gcc can generate.

</off-topic>

As for the `x - x', the Standard says (6.3.2.3p3):

An integer constant expression with the value 0,
or such an expression cast to type void *, is called
a _null pointer constant._ If a null pointer constant
is converted to a pointer type, the resulting pointer,
called a _null pointer,_ is guaranteed to compare
unequal to a pointer to any object or function.

The question of whether `x - x' is a null pointer constant
thus hinges on whether it is an integer constant expression.
The Standard defines I.C.E. in 6.6p6:

An _integer constant expression_ shall have integer
type and shall only have operands that are integer
constants, enumeration constants, character constants,
sizeof expressions whose results are integer constants,
and floating constants that are the immediate operands
of casts. [...]

Since `x - x' has operands that are impermissible in an
I.C.E., `x - x' is not an I.C.E. and hence not an N.P.C.

--
Er*********@sun .com

Aug 14 '07 #8
matevzb wrote:
>
I've ran into some fishy code that, at first glance, is buggy, but
it seems to work correctly and none of the compilers I've tried
(five so far, on various systems) gives any warnings. The code:

#include <stdio.h>

void fcn (char *str) {
This wants a pointer to char as the parameter.
if (str == '\0') {
This tests the parameter against a fixed char.
printf ("str!\n");
}
}

int main (void) {
fcn ('\0');
This passes an integer (char representation) to something that
wants a char. pointer.
return 0;
}
--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Aug 14 '07 #9
Eric Sosman wrote:
>
.... snip ...
>
Well, no, not exactly. There is no need to type-check
a NULL, because NULL is a perfectly good value for any kind
of pointer at all. The confusion (what remains of it) comes
from the fact that there are many ways to spell NULL.

Gertrude Stein never said "A NULL is a '\0' is a 0,"
but she could have.
I don't agree that '\0' is a spelling of NULL. It is a spelling of
the int value zero. The primes make it precisely an int.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Aug 14 '07 #10

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

Similar topics

3
3407
by: Bernard André | last post by:
Hi All, I posted this already today and I am really getting bananas with this issue: Using Visual Basic 6.0, I am sending SMS. These SMS can be added to an Access 2000 table by users on the network. Everything works well when executing the code step by step (F8). I can trace this in the Access table, that reacts exactly according to what I was expecting. But, but.... When running the code, it looks like the records in Access are not...
14
6347
by: Allcomp | last post by:
Hello, I have seen something really strange in VB6 If I do a Int ( (5 * 1.2)) , I receive the value 5, but I should receive 6? Is this a bug or something really "normal". I can see that if I do ? int ((5 * 1.2 + 0.0000000000000003)) I receive 6. If I add something smaller, I have 5 as a result What is strange is that If I do a ? 5*1.2, I receive 6 so (5 * 1.2)
24
4746
by: LineVoltageHalogen | last post by:
Greetings All, I was hoping that someone out there has run into this issue before and can shed some light on it for me. I have a stored procedure that essentially does a mini ETL from a source OLTP DB to a the target Operational Data Store. This is still in development so both DB's reside on the same machine for convenience. The stored proc runs successfully from within Query analyzer and this holds true on the following platforms: XP...
3
1862
by: Arnold Schrijver | last post by:
I wrote a program that draws items to the screen and maintains a set of Offset values. There was a bug in the code, because objects were positioned wrongly. While debugging I found some peculiar behavior with the overloaded Property Offsets: In class CanvasBlock: ------------------------------ Public Enum EOffsetTypes
8
1248
by: Boni | last post by:
Dear all, class A overridable sub s1(byval a as integer) end sub overridable sub s2(byval a as integer, byval b as integer) end sub end class class B inherits class A
0
1009
by: M.Posseth | last post by:
Hello , I have a strange problem when i set a reference to http://www.trostonline.de/autobest/tolwebservice.dll/wsdl/ITOLServiceInterface i end up with a logon method like this
3
2773
by: annecarterfredi | last post by:
I was getting snapshot since the database was responding very slow...here is the query that was in a snapshot: WITH TYPEINTS ( TYPEINT, COLTYPE ) AS ( VALUES ( SMALLINT(1 ), CHAR( 'INTEGER', 8) ), ( SMALLINT (2 ), CHAR( 'SMALLINT', 8) ), ( SMALLINT(3 ), CHAR( 'BIGINT', 8) ), ( SMALLINT(4 ), CHAR( 'REAL' , 8) ), ( SMALLINT(5 ), CHAR( 'DOUBLE', 8) ), ( SMALLINT(6 ), CHAR( 'CHAR', 8) ), ( SMA LLINT(7 ), CHAR( 'VARCHAR',...
2
1716
by: Victor Lin | last post by:
Now I am now developing a program that base on sqlite3 in python. But there is a strange problem. That is, all data I insert into sqlite database do not goes into file in disk. It is really strange.... Why do these data just keep in memory and discarded? All things that really store in file is the table. If I create a table, it would appears in the sqlite file.
2
1548
by: djpaul | last post by:
Hello, I have this program and when i want to load pictures it crashes at the form.showdialog()....??? Here it goes: Private Sub CmbPath_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmbPath.SelectedIndexChanged Dim Table As DataTable Dim i As Integer Dim ThumbSize As Integer = 160
1
2724
by: raylopez99 | last post by:
The below did not set off my compiler, perhaps because I set the warnings to a higher (less nag) level. Strange. FYI, no question being asked. RL double d2030;
0
8979
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
8818
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
9354
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...
1
9307
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8233
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
6790
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
6067
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
4588
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4860
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.