473,624 Members | 2,323 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointer to int, implicit conversion

[Please forgive the introduction which talks about C++ rather than C, but
I'd just like to explain how I came to be writing if(p) before I go on to
tackle C-specific issues]

Coming originally from C++, I used to do the likes of the following,
using a pointer in a conditional:
void Func(int *p)
{
if (p)
{
*p++ = 7;
*p++ = 8;
}
}

In C++, the type of conditional expressions is bool. When a pointer
is converted to bool, it becomes false if it was a null pointer, true
otherwise. (Let's not get into the issue of whether a pointer to one past
the last element of an array can compare equal to null :P)

Now writing C code, I stopped and paused for a moment today when I
wrote code like that above. It looks to me, that, in the above code, the
pointer would be converted to an int before it would be evaluated by "if".

The compiler I'm using on the machine beside me is Microsoft Visual
Studio, so it's by no means guaranteed to be 100% compliant to any C
Standard. Anyway, it accepts the above function with zero errors and zero
warning. (And yes it's in C mode, not C++ mode).

But my question is:

1) Should a Standard-compliant compiler accept an implicit conversion
from pointer type to int? (as in "if (p)")
2) If so, what exactly is supposed to happen? Do null pointers become
zero while every other address becomes 1? Somehow I doubt that. My first
guess would be that the Standard doesn't define the behaviour of
converting pointers to integer types.

By the way, I'm aware that the inversion operator, i.e. !, turns a
null pointer into 1 and every other pointer into 0, but I'm talking
specifically about a bare naked pointer without an operator applied.

And yes, I'm fully aware that I can replace if (p) with if (!!p).

The exact code that had me thinking about this was:

assert(p);

I had a function which took a pointer and asserted straight away that
it actually pointed to something. When I switched to a different compiler
on a different machine, I got an error telling me there's no implicit
conversion from pointer to integer type (as I would hope!).

I think I can recall hearing some time ago that the argument to
assert MUST be of type int. Is this true? Should I be writing:

assert(!!p);

And again, what's supposed to happen when I do assert(p)? Is the
pointer converted to an int, and then the int evaluated to see if it's
true or false? If so, then what value does the resultant int have... ? My
guess is that it's undefined by the Standard.

--
Tomás Ó hÉilidhe
Nov 20 '07 #1
19 3888
On Nov 20, 7:22 pm, Tomás Ó hÉilidhe <t...@lavabit.c omwrote:
1) Should a Standard-compliant compiler accept an implicit conversion
from pointer type to int? (as in "if (p)")
2) If so, what exactly is supposed to happen? Do null pointers become
zero while every other address becomes 1? Somehow I doubt that. My first
guess would be that the Standard doesn't define the behaviour of
converting pointers to integer types.
You've asked question 5.3 of the C FAQ. <http://c-faq.com/null/
ptrtest.html>
>
By the way, I'm aware that the inversion operator, i.e. !, turns a
null pointer into 1 and every other pointer into 0, but I'm talking
specifically about a bare naked pointer without an operator applied.

And yes, I'm fully aware that I can replace if (p) with if (!!p).

The exact code that had me thinking about this was:

assert(p);

I had a function which took a pointer and asserted straight away that
it actually pointed to something. When I switched to a different compiler
on a different machine, I got an error telling me there's no implicit
conversion from pointer to integer type (as I would hope!).

I think I can recall hearing some time ago that the argument to
assert MUST be of type int. Is this true? Should I be writing:

assert(!!p);

And again, what's supposed to happen when I do assert(p)? Is the
pointer converted to an int, and then the int evaluated to see if it's
true or false? If so, then what value does the resultant int have... ? My
guess is that it's undefined by the Standard.

--
Tomás Ó hÉilidhe
Nov 20 '07 #2
Francine.Neary:
You've asked question 5.3 of the C FAQ. <http://c-faq.com/null/
ptrtest.html>

Thanks for the link. There's a particular part I want to inquire
about:

-- beginning --
When C requires the Boolean value of an expression, a false value is
inferred when the expression compares equal to zero, and a true value
otherwise. That is, whenever one writes

if(expr)

where ``expr'' is any expression at all, the compiler essentially acts as
if it had been written as

if((expr) != 0)

--

Until now, I had thought that if, while and the middle part of a for
loop all took an "argument" whose type was int. Therefore I _thought_
that the following would always be identical:

if (a)

and:

if ((int)a)

, regardless of the type of the expression int. Putting a little more
thought into it though, I realised I violate this train of thought all
the time:

unsigned i = UINT_MAX;

if (i)

Of course, the behaviour is implementation-defined when you assign
too-big-of-a-number to an int, so we can't say for sure whether (int)i
would be true or false, but we _do_ know for sure that i is true.

So should I just forget the idea altogether that conditionals are of
type int in C? I realise that the operators ==, >, !=, etc. all evaluate
to an int, but I suppose that doesn't have to mean that if, while and the
middle part of a for have to take an int argument.

So basically, the conditionals take the value, regardless of its
type, and return false if it's zero (including a null pointer), otherwise
true. Looks like I can just keep going exactly how I was doing things in C
++. :-D

If I'm mistaken, please throw a pie in my face! One more thing, can
someone please tell me whether I have to give an int value to assert?

--
Tomás Ó hÉilidhe
Nov 20 '07 #3
Tomás Ó hÉilidhe wrote, On 20/11/07 22:36:

<snip reference to relevant FAQ entry>
Until now, I had thought that if, while and the middle part of a for
loop all took an "argument" whose type was int. Therefore I _thought_
that the following would always be identical:

if (a)

and:

if ((int)a)
<snip reasons this might be wrong>

You thought wrong for, amongst other things, the reasons you went on to
specify.
So should I just forget the idea altogether that conditionals are of
type int in C? I realise that the operators ==, >, !=, etc. all evaluate
to an int, but I suppose that doesn't have to mean that if, while and the
middle part of a for have to take an int argument.
Yes, forget that idea as it is definitely wrong.
So basically, the conditionals take the value, regardless of its
type, and return false if it's zero (including a null pointer), otherwise
true. Looks like I can just keep going exactly how I was doing things in C
++. :-D
I believe the rules are the same as for C++ because I believe that C++
inherited them from C.
If I'm mistaken, please throw a pie in my face!
Can't we throw one anyway?
One more thing, can
someone please tell me whether I have to give an int value to assert?
I can't remember the exact rule, but I believe that in C89/C90/C95 (the
most commonly fully implemented versions of the standard) you are not
allowed to assert on the value of a pointer directly. I believe this
changed in C99.
--
Flash Gordon
Nov 20 '07 #4
On Tue, 20 Nov 2007 22:36:03 GMT, Tomás Ó hÉilidhe <to*@lavabit.co m>
wrote in comp.lang.c:
Francine.Neary:
You've asked question 5.3 of the C FAQ. <http://c-faq.com/null/
ptrtest.html>


Thanks for the link. There's a particular part I want to inquire
about:

-- beginning --
When C requires the Boolean value of an expression, a false value is
inferred when the expression compares equal to zero, and a true value
otherwise. That is, whenever one writes

if(expr)

where ``expr'' is any expression at all, the compiler essentially acts as
if it had been written as

if((expr) != 0)

--

Until now, I had thought that if, while and the middle part of a for
loop all took an "argument" whose type was int. Therefore I _thought_
that the following would always be identical:

if (a)

and:

if ((int)a)

, regardless of the type of the expression int. Putting a little more
thought into it though, I realised I violate this train of thought all
the time:

unsigned i = UINT_MAX;

if (i)

Of course, the behaviour is implementation-defined when you assign
too-big-of-a-number to an int, so we can't say for sure whether (int)i
would be true or false, but we _do_ know for sure that i is true.

So should I just forget the idea altogether that conditionals are of
type int in C? I realise that the operators ==, >, !=, etc. all evaluate
to an int, but I suppose that doesn't have to mean that if, while and the
middle part of a for have to take an int argument.
An expression evaluated in a Boolean context in C yields a result of
type int with the value 0 or 1. That has nothing to do with what the
operands are.

For example:

double d1 = 3.9 d2 = 3.1;

if (d1 == d2)
{
/* stuff */
}

I assume that if you wrote the code above, you would be very, very
surprised if the statements designated by /* stuff */ were executed.
Yet if there was an explicit conversion to int, both d1 and d2 would
be truncated to 3, and /* stuff */ would be executed.
So basically, the conditionals take the value, regardless of its
type, and return false if it's zero (including a null pointer), otherwise
true. Looks like I can just keep going exactly how I was doing things in C
++. :-D
Basically, expressions operate on values. If there are multiple
values, rvalues or lvalues, in an expression, the standard promotions
are performed, just as if you perform an operation like addition or
subtraction on two different types.

Based on the as-if rule, of course, Boolean expressions do not
actually have to produce an actual int with a value of 0 or 1. In the
d1 and d2 example above, the compiler generates machine language to do
the comparison and uses some processor specific mechanism to execute
/* stuff */ or jump over it.

On the other hand, if you have code like this (inside a function):

double d1 = /* some value */, d2 = /* some value */;
int equal;

/* some operations that might modify the values of */
/* d1 and/or d2 */

equal = (d1 == d2);

....then the program must generate code to produce an actual int value
of 0 or 1 and store it in "equal". Assuming that it the value of
equal is later used, so it can't be optimized away.
If I'm mistaken, please throw a pie in my face! One more thing, can
someone please tell me whether I have to give an int value to assert?
Flash's memory on this question is correct. Prior to C99, the C
standard defined the assert macro to take an int parameter, although
many (perhaps even most) compilers accepted a pointer with an implicit
test against 0.

From 1999 on, the C standard allows any scalar type for the
expression, meaning integer types, floating point types, and pointers.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Nov 21 '07 #5
Tomás Ó hÉilidhe wrote:
....
So basically, the conditionals take the value, regardless of its
type, and return false if it's zero (including a null pointer), otherwise
Conditionals do not return false (or true); they result in one part of
the code or another being executed. They do this based upon whether or
not the conditional expression compares equal to 0. That's not the same
as saying it's the same as 0. An expression can be zero only if it has
arithmetic type. Pointers do not have an arithmetic type, so it's not
meaningful to say that they are 0, but because of the rules for null
pointer constants, pointers compare equal to zero when they are null.
Nov 21 '07 #6
On Nov 21, 9:36 am, James Kuyper <jameskuy...@ve rizon.netwrote:
Tomás Ó hÉilidhe wrote:

...
So basically, the conditionals take the value, regardless of its
type, and return false if it's zero (including a null pointer), otherwise

Conditionals do not return false (or true); they result in one part of
the code or another being executed. They do this based upon whether or
not the conditional expression compares equal to 0. That's not the same
as saying it's the same as 0. An expression can be zero only if it has
arithmetic type. Pointers do not have an arithmetic type, so it's not
meaningful to say that they are 0, but because of the rules for null
pointer constants, pointers compare equal to zero when they are null.
If You are working in a 64 bit machine then it would make a difference
otherwise if(p) doesn't have any issue in 32 bit machine
If we really want to use a language efficiently and safely, Then we
should
try to express our intension much clearly and specifically in C
language.
instead of allowing the compiler to assume thing, this a very bad
Practice.
This discussion was not useful and was repitative

RUV
Nov 21 '07 #7
In article <nj************ *******@news.in digo.ie>
Tomás Ó hÉilidhe <to*@lavabit.co mwrote:
[snippage]
Until now, I had thought that if, while and the middle part of a for
loop all took an "argument" whose type was int. ...
If they were functions, they would take actual arguments, and --
assuming they were not something peculiar like printf(), i.e.,
not a "variadic" function -- the argument would have to have a
fixed type. But they are not functions; they are keywords.

The way to think about them, in my opinion -- which I admit is
a bit colored by past work on compilers -- is to say that they
take an "expression tree node", which is a compiler internal
data structure, and start by examining the type of this node.
If the type is "pointer to T" (where T is any valid type -- if
T were not a valid type we would not have gotten to this point
inside the compiler in the first place), they generate code to
compare the pointer against a null pointer of that same type.

If the expression tree node has some other type, such as "double",
the compiler generates a comparison against 0.0, or whatever else
is appropriate. If the node has a type that is already known to
be "sufficient ly boolean", whatever that means given the compiler
and the target architecture, the compiler may not have to generate
any code at all. (As an example of the latter, if the node is not
a simple variable, but instead is something like (COMPAREOP x y),
the compiler need only ask its expression-evaluator to generate
the appropriate comparison-for-condition-codes sequence, then emit
the appropriate branch. This assumes the target CPU has condition
codes, of course.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 21 '07 #8
In article
<a3************ *************** *******@c30g200 0hsa.googlegrou ps.com>,
Rakesh UV <uv******@gmail .comwrote on Wednesday 21 Nov 2007 12:59 pm:
On Nov 21, 9:36 am, James Kuyper <jameskuy...@ve rizon.netwrote:
>Tomás Ó hÉilidhe wrote:

...
So basically, the conditionals take the value, regardless of
its
type, and return false if it's zero (including a null pointer),
otherwise

Conditionals do not return false (or true); they result in one part
of the code or another being executed. They do this based upon
whether or not the conditional expression compares equal to 0. That's
not the same as saying it's the same as 0. An expression can be zero
only if it has arithmetic type. Pointers do not have an arithmetic
type, so it's not meaningful to say that they are 0, but because of
the rules for null pointer constants, pointers compare equal to zero
when they are null.

If You are working in a 64 bit machine then it would make a difference
otherwise
What would make a difference? Comparing pointers against literal zero?
If so, I can't see why?
if(p) doesn't have any issue in 32 bit machine
I believe it should be issue-free on any N-bit system that supports
Standard C.
If we really want to use a language efficiently and safely, Then we
should try to express our intension much clearly and specifically in C
language. instead of allowing the compiler to assume thing,
I agree here. Compilers can handle obscure and "clever" constructs and
obfuscated code, but the maintenance programmer may not do so. High
level language source is for human consumption, otherwise we might as
well program in machine code.
this a very bad Practice.
This discussion was not useful and was
repitative
It's likely to be useful to lurkers and newbies, who are perhaps the
greatest beneficiaries of most newsgroups.

Nov 21 '07 #9
Jack Klein:
For example:

double d1 = 3.9 d2 = 3.1;

if (d1 == d2)
{
/* stuff */
}

I assume that if you wrote the code above, you would be very, very
surprised if the statements designated by /* stuff */ were executed. Yet
if there was an explicit conversion to int, both d1 and d2 would be
truncated to 3, and /* stuff */ would be executed.

That would never happen. If I had:

void Func(int);

and called it as follows:

Func( 2.0 * 3.7 );

, then the entire expression would be converted to int _after_ it's
evaluated. It won't becomes "2 * 3".

(Somehow I think we misunderstand each other here because I've read a few
of your other posts and you seem to know your stuff, so it's surprising
to me that you'd come out with something like this).

--
Tomás Ó hÉilidhe
Nov 21 '07 #10

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

Similar topics

2
3085
by: Russell Reagan | last post by:
In a newer version of a chess program I am writing, I have created classes that are (more or less) drop in replacements for things that used to be plain old integer or enumerated variables (colors, piece types, squares, etc.). To accomplish this, I used implicit conversions. For instance, a color used to be: typedef int Color; // and a few constants... Now a color is (paraphrased):
1
1855
by: Christophe Poucet | last post by:
Hellom I have an issue with implicit conversions. Apparently when one calls an operator on a class Y which has a conversion operator to class X which has the operator . Sadly it will not do implicit conversion for this case, however if instead of class X we just use a pointer then the implicit conversion will work. Anyone have any ideas why it will not do implicit conversion?
3
2069
by: Siemel Naran | last post by:
Here is a question about implicit conversion from T (&) to ptrcarray<T>. I wrote a class template <class T> struct ptrcarray { T * array; size_t size;
11
7605
by: Steve Gough | last post by:
Could anyone please help me to understand what is happening here? The commented line produces an error, which is what I expected given that there is no conversion defined from type double to type Test. I expected the same error from the following line, but it compiles fine. The double is silently truncated to an int and then fed in to the implicit conversion operator. Why does this happen? Is there any way that I can keep the implicit...
9
2075
by: Girish | last post by:
Im trying to understand implicit type conversions from object -> string and vice versa. I have two classes, one Driver and one called StringWrapper. These are just test classes that try and emulate the pattern im trying to follow in an existing project. These are my steps: 1) I have a method "printMe" existing in the application which originally used to take in a string. This method is static and sits in the Driver
11
12751
by: Aaron Queenan | last post by:
Given the classes: class Class { public static implicit operator int(Class c) { return 0; } } class Holder
3
2914
by: bb | last post by:
Hi, Please could you clarify why 'implicit conversion' does not take place while assigning an iterator to reverse_iterator. However, it happens while initializing/constructing. e.g. typedef std::map<int, std::stringMIS; MIS m1;
3
2467
by: Jess | last post by:
Hello, I can perform implicit conversion through constructor, like class A{ public: A(int x):a(x){}; int a; };
1
1832
by: drop | last post by:
Hi all, I'd like to know if it's possible to declare an implicit type conversion for when I use declarative Synthax in html. For example, when I have the DropDownList, I can declatively set it's Selected value like this : SelectedValue='<%# Bind("TaxCondition") %>'. In this case, TaxCondition is an int, and the conversion from int to string and string to int is made automatically.
0
8242
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
8177
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
8681
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8629
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
8341
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
7170
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...
0
4084
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
4183
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1793
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.