473,425 Members | 1,807 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,425 software developers and data experts.

Questions, please

bml
Q1:
int i = 0;
char *p = i;

Is this assign 0 to p or assigning the value pointed by p to 0?
Is this a problem since p has not been initialized, it could point to any
place in memory and assign a value to it could cause access violation?

Q2:
Why might explicit casts on malloc's return value, as in
int *ip = (int *)malloc(10 * sizeof(int));
be a bad style?

Q3:
Why casting in C is so "dangerous" sometimes?

Thanks a lot!



Nov 14 '05
59 2591
Dan Pop wrote:

I don't get it. What's wrong with

double pi = 3.14;
(float)pi;

but would be OK with the hypothetical

float(pi);

???

I freely admit that I like the C++ way better, but I can't find anything
wrong with the C way of doing it. There is no fundamental difference
between (float)pi and float(pi). The latter merely saves a couple
of parentheses when a more complex expression is converted.


The syntax might be nasty when casting to more complicated
types:

(const struct something *)ptr

would presumably come out looking something like

const struct something *(ptr)

.... and the latter might be harder for compilers -- and humans --
to parse than the former.

Functionally, though, I'm with Dan: I don't see any
semantic difference between the proposal and current practice.
C needs to convert values from one type to another, and the
set of types is extensible by the programmer. Therefore, C
needs an extensible notation to express the conversions. One
might quarrel with the chosen form, but I think it would be
hard to quarrel with the underlying need.

--
Er*********@sun.com
Nov 14 '05 #51
Dan Pop wrote:
CBFalconer <cb********@yahoo.com> writes:
Eric Sosman wrote:

... snip ...

A cast is an operator, just like `+' or `%'. Almost all[*]
C operators work with the values of their operand or operands,
and none[**] works with the representations.


And, IMO, a cast is another example of an overloaded C construct.
I consider that it would have been better to limit casts to
altering the 'typewise' interpretation of a bit pattern, provided
that the size of that pattern is the same for the original and the
cast type. After that there should specific functions to perform
the various transformations.


I don't get it. What's wrong with

double pi = 3.14;
(float)pi;

but would be OK with the hypothetical

float(pi);


Bear in mind that this is all blue-skying. I would like
"(float)pi;" to fail with an error message to the effect "float
and typeof pi are not the same size". However "float(pi);" would
perform the necessary transformatins. The first simply revises
the compilers view of the type involved, the second does real
modifications to the underlying representation.

--
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 #52
CBFalconer wrote:

Bear in mind that this is all blue-skying. I would like
"(float)pi;" to fail with an error message to the effect "float
and typeof pi are not the same size". However "float(pi);" would
perform the necessary transformatins. The first simply revises
the compilers view of the type involved, the second does real
modifications to the underlying representation.


Sorry for misunderstanding the (blue-sky) proposal.
But why would anyone want the semantics you suggest? The
main drawback, I think is that they'd be utterly unportable:

- Since the implementation specifies the sizes of the
various types, `(float)pi' would compile on some
machines and toss errors on others.

- Since the implementation specifies the representations
of the various types, `(float)pi' would yield different
values on different systems where it happened to compile,
and it's even possible that some of these would be trap
representations.

Perhaps the construct might be of some use in sorting out
the three flavors of `char', but I'm having trouble coming up
with other situations where I'd want such a thing. Would you
mind posting a few descriptions of where such a beast would
be useful?

FWIW, a sort of "reinterpretation" can sometimes be had
by type-punning through pointers:

int kids_dont = 42;
float *try_this = (float*)&kids_dont;
float at_home = *try_this;

.... with all the well-known drawbacks.

--
Er*********@sun.com
Nov 14 '05 #53
Eric Sosman wrote:
CBFalconer wrote:

Bear in mind that this is all blue-skying. I would like
"(float)pi;" to fail with an error message to the effect "float
and typeof pi are not the same size". However "float(pi);" would
perform the necessary transformatins. The first simply revises
the compilers view of the type involved, the second does real
modifications to the underlying representation.
Sorry for misunderstanding the (blue-sky) proposal.
But why would anyone want the semantics you suggest? The
main drawback, I think is that they'd be utterly unportable:

- Since the implementation specifies the sizes of the
various types, `(float)pi' would compile on some
machines and toss errors on others.

- Since the implementation specifies the representations
of the various types, `(float)pi' would yield different
values on different systems where it happened to compile,
and it's even possible that some of these would be trap
representations.


Is that bad? I would consider it to point out the
non-portability.

Perhaps the construct might be of some use in sorting out
the three flavors of `char', but I'm having trouble coming up
with other situations where I'd want such a thing. Would you
mind posting a few descriptions of where such a beast would
be useful?

FWIW, a sort of "reinterpretation" can sometimes be had
by type-punning through pointers:

int kids_dont = 42;
float *try_this = (float*)&kids_dont;
float at_home = *try_this;

... with all the well-known drawbacks.


Yes, but instead we find people using unions and wandering off
baffled and muttering to themselves. If a type name (or the
equivalent via a typedef) used as a function did the actual
conversion, the meaning of "float(kids_dont)" would, I think, be
clear to both the user and the compiler. The above "drawbacks"
would be signalled by an immediate error in "(float)kids_dont".
The above coding, with its drawbacks, would not be affected.

Since it will never happen it is not worth much discussion. I
brought it up primarily as an example of Cs overloading of
symbols.

--
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 #54
Richard Heathfield <do******@address.co.uk.invalid> wrote in message news:<bv**********@sparta.btinternet.com>...
Peter Nilsson wrote:
"Richard Heathfield" <do******@address.co.uk.invalid> wrote in message
news:bv**********@sparta.btinternet.com...
Peter Nilsson wrote:
> Richard Heathfield <do******@address.co.uk.invalid> wrote in message
> news:<bv**********@titan.btinternet.com>...
>> bml wrote:
>> >
>> > Q2:
>> > Why might explicit casts on malloc's return value, as in
>> > int *ip = (int *)malloc(10 * sizeof(int));
>> > be a bad style?
>>
>> (1) all code should either do something good or stop something bad
>> happening; a cast on malloc does neither.
>
> AKAICS, neither does...
>
> va_list ap = 0;
I misremembered... va_list ap = { 0 };


Yup.
This code gives ap a known value,


What _value_ would that be? What is the benefit of this known value (sic)?


Good question. :-)

Your followup makes it clear that your choice of va_list wasn't random,


It was a very specific example of a 'useless' construct which you have
posted previously.
> ...or...
>
> while (yadda)
> {
> continue;
> }

This shows that the loop is "intentionally left blank" to use that awful
phrase, and thus has a certain self-documenting value.


'Self-documenting' is how some malloc casters describe the malloc cast.


Yes. I'm not convinced by that argument, however. Otherwise, surely instead
of:
printf("%f\n", d);

they'd write:

(void)(int)((int(*)(const char *, ...))printf((const char *)"%f\n",
(double)d));

Yes, you could argue that that's self-documenting, but it's hardly clearer,
is it?


And surely (sic), all loops should finish with a continue statement?

This is really a sad argument as style practices are rarely taken to
their logical extreme.
Irrespective of 'cost', if a redundant token 'adds' something to the above
code in your mind, then couldn't a redundant cast also 'add' something in
the minds of some other C programmers?


But the cast isn't redundant - that is, code with it does not have the same
meaning as code without it.


How is the meaning of the code different? Most function calls are
context sensitive.
An explicit conversion is performed that
otherwise would not be performed.


In correct code it's the _same_ conversion.
> Yet there is at least one clc regular who chooses to utilise such
> practices. ;)
>
>> (2) the conversion can actually cause some compilers not to warn you
>> if you forgot to #include <stdlib.h>
>
> Explicit redundant initialisation of all automatic variables can also
> hide bugs.

On balance, I find that the benefits outweigh the costs.


That is _your_ finding, in _this_ case.


That's right.
Yet I've yet to see yourself
vehemently thrusting this as the One True Style on newbies, let alone
other similarly competent C experts who have disagreed with your style.


That's for the very obvious reason that there are advantages and
disadvantages to both styles.


How is malloc casting different? There are advantages and
disadvanteges to either method. It's a question of how we (as
individuals) value them.
> and they feel that what they gain in
> 'aesthetics' outways the cons.

Form follows function.


Interesting. Would you say that void * and its associated deliberate type
weakness was a _good_ choice for the C language?


Yes.


Why?

I agree it's functional. But it has it's limitations and problems.
Would you say it was the
_best_ choice?


I can't think of a better one off-hand (although I wish it also applied to
function pointers, and that void ** had the same kinds of guarantees that
come with void *).


C++ isn't a better choice for purely generic programming? You think
the inherent problems of a type weak void * are _better_ than classes,
templates and overloaded function support?

--
Peter
Nov 14 '05 #55
Peter Nilsson wrote:
It was a very specific example of a 'useless' construct which you have
posted previously.
You follow these matters much more keenly than I, it seems. :-) I don't
recall posting a va_list ap = {0} example myself.
>> > ...or...
>> >
>> > while (yadda)
>> > {
>> > continue;
>> > }
>>
>> This shows that the loop is "intentionally left blank" to use that
>> awful phrase, and thus has a certain self-documenting value.
>
> 'Self-documenting' is how some malloc casters describe the malloc cast.


Yes. I'm not convinced by that argument, however. Otherwise, surely
instead of:
printf("%f\n", d);

they'd write:

(void)(int)((int(*)(const char *, ...))printf((const char *)"%f\n",
(double)d));

Yes, you could argue that that's self-documenting, but it's hardly
clearer, is it?


And surely (sic), all loops should finish with a continue statement?


All /empty/ loops should finish with a continue statement. :-)
This is really a sad argument as style practices are rarely taken to
their logical extreme.
If you find it a sad argument, I'm happy to end the discussion right here
(without prejudice on either side). I have no wish to sadden you, or indeed
anyone else.
> Irrespective of 'cost', if a redundant token 'adds' something to the
> above code in your mind, then couldn't a redundant cast also 'add'
> something in the minds of some other C programmers?


But the cast isn't redundant - that is, code with it does not have the
same meaning as code without it.


How is the meaning of the code different?


With the cast, it contains an explicit conversion. That's what a cast /is/.
An explicit conversion is performed that
otherwise would not be performed.


In correct code it's the _same_ conversion.


It's explicit, as opposed to implicit. I agree that the /outcome/ is the
same - in correct code. In incorrect code, however, it may not be.

<snip>
> Yet I've yet to see yourself
> vehemently thrusting this as the One True Style on newbies, let alone
> other similarly competent C experts who have disagreed with your style.


That's for the very obvious reason that there are advantages and
disadvantages to both styles.


How is malloc casting different? There are advantages and
disadvanteges to either method. It's a question of how we (as
individuals) value them.


advantages disadvantages

cast can hide a bug
none higher maintenance costs
more typing
obscures code

no cast doesn't hide bug
lower maintenance costs none
less typing
clear code

That's how I see it. Clearly, your mileage varies.
>> > and they feel that what they gain in
>> > 'aesthetics' outways the cons.
>>
>> Form follows function.
>
> Interesting. Would you say that void * and its associated deliberate
> type weakness was a _good_ choice for the C language?


Yes.


Why?


Because it gives me a decent amount of slack in the type system, which I can
use to good effect.
I agree it's functional. But it has it's limitations and problems.
What doesn't, in this life?

> Would you say it was the
> _best_ choice?


I can't think of a better one off-hand (although I wish it also applied
to function pointers, and that void ** had the same kinds of guarantees
that come with void *).


C++ isn't a better choice for purely generic programming?


I thought you were asking me about C, not C++. If you have a C++ question,
please ask in comp.lang.c++.
You think
the inherent problems of a type weak void * are _better_ than classes,
templates and overloaded function support?


If you want C++, you know where to find it.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #56
"Joona I Palaste" <pa*****@cc.helsinki.fi> wrote:
Hmm, interesting. Try this for a program to calculate the
sum of ten numbers:

#include <stdio.h>
int main(void) {
int a[(int)10];
int i;
int sum=(int)0;
for ((int)(i=(int)0); (int)((int)i<(int)10); (int)i++) {
Perhaps the initialisation part of a for statement should
have an extra cast to (void) as it is evaluated as a void
statement? :-)
(void)(int)(((int *)a)[(int)i]=(int)i);
}
for ((int)(i=(int)0); (int)((int)i<(int)10); (int)i++) {
(void)(int)(sum=(int)((int)sum+(int)((int *)a)[(int)i])));
There are one too many closing parentheses at the end of this line.
}
(void)(int)((int(*)(const char *, ...))printf((const char *)
"The sum is %d\n", (int)sum));
return (int)0;
}


--
Simon.
Nov 14 '05 #57
On Wed, 04 Feb 2004 15:00:02 -0500, Bubba <bu**@jkd-nospam-com.com>
wrote:
On Wed, 04 Feb 2004 13:30:28 -0500, Eric Sosman wrote:
CBFalconer wrote:

Bear in mind that this is all blue-skying. I would like
"(float)pi;" to fail with an error message to the effect "float
and typeof pi are not the same size". [.... or] simply revise[]
the compilers view of the type involved [....]

Like Ada UNCHECKED_CONVERSION or PL/I UNSPEC.
Sorry for misunderstanding the (blue-sky) proposal.
But why would anyone want the semantics you suggest? The
main drawback, I think is that they'd be utterly unportable:


Apparently the C++ standardization committee would want them. C++ has
static_cast and reinterpret_cast for this very thing, and, no, I
personally don't endorse them.

No, C++ static_cast and reinterpret_cast, in spite of their names,
convert values possibly (and for some cases always) resulting in a
change of representation. There is no cast in C or C++ that is
portably guaranteed to just apply a different type to the same
representation -- although there are in both languages on any given
implementation sets of types which have the same representation, and
casting among *those* types keeps the representation (duh!).

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #58
"Dave Thompson" <da*************@worldnet.att.net> wrote in message
news:k6********************************@4ax.com...
There is no cast in C or C++ that is
portably guaranteed to just apply a different type to the same
representation


int a = 42;
float b = *((float*)&a); /* :-) */

Of course this is not portable, how can you *portably* interpret
a 'float' from an 'int' bit pattern anyway? Applying a different
type to the same representation is a rather dubious requirement,
IMNSHO. (Yes, I know that it was your point.)

Peter
Nov 14 '05 #59
On Sun, 15 Feb 2004 15:35:43 -0000, "Peter Pichler" <pi*****@pobox.sk>
wrote:
"Dave Thompson" <da*************@worldnet.att.net> wrote in message
news:k6********************************@4ax.com...
There is no cast in C or C++ that is
portably guaranteed to just apply a different type to the same
representation
int a = 42;
float b = *((float*)&a); /* :-) */

But the cast doesn't do it, the dereference does, by "creating" an
lvalue that designates the object with a different type. As far as the
cast goes, float* is not required to have the same representation as
int* -- although in practice it always does; on machines where data
pointers vary it is character and void pointers that are different.
Of course this is not portable, how can you *portably* interpret
a 'float' from an 'int' bit pattern anyway? Applying a different
type to the same representation is a rather dubious requirement,
IMNSHO. (Yes, I know that it was your point.)

In general yes, although my point was really that even in those cases
where it does make sense C and C++ still don't guarantee it.

Cf Ada, where you have substantial control over some representations,
and extensive inquiries into all of them which can verify that they
are as you expect, so it can be portable to do this, at least to the
extent that it will either work or give a clear error which you might
well be able to recover from; nothing undefined or unpredictable.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #60

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

Similar topics

0
by: Boris Ammerlaan | last post by:
This notice is posted about every week. I'll endeavor to use the same subject line so that those of you who have seen it can kill-file the subject; additionally, Supersedes: headers are used to...
0
by: softwareengineer2006 | last post by:
All Interview Questions And Answers 10000 Interview Questions And Answers(C,C++,JAVA,DOTNET,Oracle,SAP) I have listed over 10000 interview questions asked in interview/placement test papers for...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
1
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...
0
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...
0
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...

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.