Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c > #67931 > unrolled thread
| Started by | Alla _ <modelling.data@gmail.com> |
|---|---|
| First post | 2015-08-21 04:39 -0700 |
| Last post | 2015-08-30 02:14 -0700 |
| Articles | 20 on this page of 47 — 12 participants |
Back to article view | Back to comp.lang.c
Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-21 04:39 -0700
Re: Initializing sum to zero wouldn't compile James Kuyper <jameskuyper@verizon.net> - 2015-08-21 07:54 -0400
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-21 05:27 -0700
Re: Initializing sum to zero wouldn't compile Keith Thompson <kst-u@mib.org> - 2015-08-21 10:28 -0700
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-21 11:15 -0700
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-21 05:30 -0700
Re: Initializing sum to zero wouldn't compile Ike Naar <ike@iceland.freeshell.org> - 2015-08-21 12:40 +0000
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-21 11:16 -0700
Re: Initializing sum to zero wouldn't compile Siri Cruz <chine.bleu@yahoo.com> - 2015-08-21 07:41 -0700
Re: Initializing sum to zero wouldn't compile Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-08-21 10:56 -0400
Re: Initializing sum to zero wouldn't compile Joe Pfeiffer <pfeiffer@cs.nmsu.edu> - 2015-08-21 09:28 -0600
Re: Initializing sum to zero wouldn't compile Barry Schwarz <schwarzb@dqel.com> - 2015-08-21 10:02 -0700
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-21 11:21 -0700
Re: Initializing sum to zero wouldn't compile Barry Schwarz <schwarzb@dqel.com> - 2015-08-21 22:27 -0700
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-22 02:25 -0700
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-22 03:50 -0700
Re: Initializing sum to zero wouldn't compile Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-08-22 13:18 +0100
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-22 11:21 -0700
Re: Initializing sum to zero wouldn't compile Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-08-22 21:55 +0100
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-26 01:36 -0700
Re: Initializing sum to zero wouldn't compile Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-08-26 11:24 +0100
Re: Initializing sum to zero wouldn't compile Barry Schwarz <schwarzb@dqel.com> - 2015-08-22 17:17 -0700
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-26 01:26 -0700
Re: Initializing sum to zero wouldn't compile Barry Schwarz <schwarzb@dqel.com> - 2015-08-26 02:27 -0700
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-26 04:21 -0700
Re: Initializing sum to zero wouldn't compile Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-08-26 12:37 +0100
Re: Initializing sum to zero wouldn't compile Richard Heathfield <rjh@cpax.org.uk> - 2015-08-26 13:06 +0100
Re: Initializing sum to zero wouldn't compile Bartc <bc@freeuk.com> - 2015-08-26 13:43 +0100
Re: Initializing sum to zero wouldn't compile Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-08-26 14:03 +0100
Re: Initializing sum to zero wouldn't compile Richard Heathfield <rjh@cpax.org.uk> - 2015-08-26 14:06 +0100
Re: Initializing sum to zero wouldn't compile Tim Rentsch <txr@alumni.caltech.edu> - 2015-09-06 15:14 -0700
Re: Initializing sum to zero wouldn't compile Keith Thompson <kst-u@mib.org> - 2015-08-26 11:38 -0700
Re: Initializing sum to zero wouldn't compile Keith Thompson <kst-u@mib.org> - 2015-08-26 11:44 -0700
Re: Initializing sum to zero wouldn't compile Barry Schwarz <schwarzb@dqel.com> - 2015-08-22 10:49 -0700
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-22 11:16 -0700
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-29 07:19 -0700
Re: Initializing sum to zero wouldn't compile Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-08-29 15:35 +0100
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-30 02:11 -0700
Re: Initializing sum to zero wouldn't compile Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-08-30 12:28 +0100
Re: Initializing sum to zero wouldn't compile Keith Thompson <kst-u@mib.org> - 2015-08-30 15:02 -0700
Re: Initializing sum to zero wouldn't compile Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-08-30 22:36 +0100
Re: Initializing sum to zero wouldn't compile Keith Thompson <kst-u@mib.org> - 2015-08-30 16:10 -0700
Re: Initializing sum to zero wouldn't compile Bartc <bc@freeuk.com> - 2015-08-31 00:14 +0100
Re: Initializing sum to zero wouldn't compile Keith Thompson <kst-u@mib.org> - 2015-08-30 19:56 -0700
Re: Initializing sum to zero wouldn't compile Bartc <bc@freeuk.com> - 2015-08-29 16:57 +0100
Re: Initializing sum to zero wouldn't compile Bartc <bc@freeuk.com> - 2015-08-29 17:37 +0100
Re: Initializing sum to zero wouldn't compile Alla _ <modelling.data@gmail.com> - 2015-08-30 02:14 -0700
Page 2 of 3 — ← Prev page 1 [2] 3 Next page →
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-08-26 11:24 +0100 |
| Message-ID | <87d1ya9wkd.fsf@bsb.me.uk> |
| In reply to | #68377 |
Alla _ <modelling.data@gmail.com> writes:
>> > for ( i = 0; i < 3; i++)
>> > {
>> > scanf ("%f", &element);
<snip>
>> > }
<snip>
> Thank you for your questions, they are very helpful.
> Actually, I hoped that I am testing scanf by using
> if (n - element == 0 || element == 0 ). Now I see
> that I don't understand what "to test scanf" means.
> I would be grateful if you explain this.
I mean you should check that some valid input was read. If the person
using your program enters "twelve" instead of "12" scanf will fail. The
variable "element" will have *some* value (it will either be what's
called "indeterminate" or it will be the value from the last time round
the loop) but in nether case should you report and average using it.
So, what to do? scanf tells you, by the value returned, the number of
items read, so you can write
if (scanf("%lf", &element) == 1) {
/* do something with the data */
}
The other side is what to do when there is an input problem.
Unfortunately, your example is rather artificial so it's hard to know
what the right thing to do it. It's ironic, but a more complex program
will have a simpler way to handle this error. For example
int n = 0;
double sum = 0;
while (scanf("%lf", &element) == 1) {
n += 1;
sum += element;
}
if (n > 0)
printf("The average of your %n numbers is %g\n", n, sum/n);
> As to numbers like 1.0, these are indeed float values,
> but I made the program test for these ones and discard
> them as invalid, because if the user enters, for example, 1 or 2,
> the program will consider them as float values, i.e. 1.0, if
> I understand that correctly.
I'm still baffled by why you want to exclude input like 1, 1.0, 1e1, 0,
0.0, 0e100 and so on. They are all perfectly reasonable numbers. Why
can't I enter 1 2 3 and get the answer 2? It's perplexing.
> "As to your question, what is the value of i after
> the loop if it ran to completion? What value does it have
> if the loop was terminated with a break?" The value of i
> upon completion is 2 (after user enters 3 values from i=0 to i=2).
No. Check again.
> When the loop is terminated with break statement, the value of i can
> be anything from 0 to 2, depending when the user enters the "invalid"
> value.
Yes. That distinction is important because once you get rid of the
funny "is_float" variable, and start checking the result of scanf, it
would offer a simple way to tell if you got all three numbers.
--
Ben.
[toc] | [prev] | [next] | [standalone]
| From | Barry Schwarz <schwarzb@dqel.com> |
|---|---|
| Date | 2015-08-22 17:17 -0700 |
| Message-ID | <4m3itahdhql900hjkegsqtflvsajjsd0hp@4ax.com> |
| In reply to | #68033 |
On Sat, 22 Aug 2015 11:21:32 -0700 (PDT), Alla _
<modelling.data@gmail.com> wrote:
<snip 70+ lines of obsolete code>
If you are going to republish the code, there is no need to quote the
old version.
>Thank you so much. Feel ashamed about forgetting such
>basic but important issues as braces after the if.
>I have corrected these errors. Thank you!
>Actually, with this version I am trying to test
>scanf for invalid inputs, such as integers or 0.
>
>// a program that calculates the average of an array
>of 3 floating-point values
>
>#include <stdio.h>
>#include <stdbool.h>
>
>int main (void)
>{
> float values[3];
> float element, average;
> float sum = 0;
> int i = 0, n = 0;
> bool is_float;
>
>
> printf ("Please, enter 3 floating values: \n");
>
> do
> {
> scanf ("%f", &element);
>
> is_float = 1;
> n = (int) element;
Why did you use a cast here? (There might be a valid reason. Tell us
yours.)
> i++;
>
> if (n - element == 0 || element == 0 )
What does the second comparison give you? If the first comparison is
false, can the second comparison ever be true?
Why do you consider 0 or 27.0 invalid values?
> {
> is_float = 0;
> printf ("Sorry, invalid input\n");
> break;
> }
>
> else
> {
> values[i] = element;
> sum += values[i];
> }
>
> }
> while (i < 3);
>
> printf ("The average of 3 values is %.2f\n", average = sum / 3);
Why did you decide to limit the output to two decimal places?
> return 0;
>}
>
>Same with for loop:
Multiple version with different algorithms might make for an
interesting discussion. Multiple versions where the only difference
is your choice of loop control do not. (Or did the book ask for two
different types of loops?)
--
Remove del for email
[toc] | [prev] | [next] | [standalone]
| From | Alla _ <modelling.data@gmail.com> |
|---|---|
| Date | 2015-08-26 01:26 -0700 |
| Message-ID | <b5f85a9f-fbbb-4a6e-9df8-7048a301428e@googlegroups.com> |
| In reply to | #68069 |
On Sunday, August 23, 2015 at 4:17:35 AM UTC+4, Barry Schwarz wrote:
> On Sat, 22 Aug 2015 11:21:32 -0700 (PDT), Alla _
> <modelling.data@gmail.com> wrote:
>
> <snip 70+ lines of obsolete code>
>
> If you are going to republish the code, there is no need to quote the
> old version.
>
> >Thank you so much. Feel ashamed about forgetting such
> >basic but important issues as braces after the if.
> >I have corrected these errors. Thank you!
> >Actually, with this version I am trying to test
> >scanf for invalid inputs, such as integers or 0.
> >
> >// a program that calculates the average of an array
> >of 3 floating-point values
> >
> >#include <stdio.h>
> >#include <stdbool.h>
> >
> >int main (void)
> >{
> > float values[3];
> > float element, average;
> > float sum = 0;
> > int i = 0, n = 0;
> > bool is_float;
> >
> >
> > printf ("Please, enter 3 floating values: \n");
> >
> > do
> > {
> > scanf ("%f", &element);
> >
> > is_float = 1;
> > n = (int) element;
>
> Why did you use a cast here? (There might be a valid reason. Tell us
> yours.)
>
> > i++;
> >
> > if (n - element == 0 || element == 0 )
>
> What does the second comparison give you? If the first comparison is
> false, can the second comparison ever be true?
>
> Why do you consider 0 or 27.0 invalid values?
>
> > {
> > is_float = 0;
> > printf ("Sorry, invalid input\n");
> > break;
> > }
> >
> > else
> > {
> > values[i] = element;
> > sum += values[i];
> > }
> >
> > }
> > while (i < 3);
> >
> > printf ("The average of 3 values is %.2f\n", average = sum / 3);
>
> Why did you decide to limit the output to two decimal places?
>
> > return 0;
> >}
> >
> >Same with for loop:
>
> Multiple version with different algorithms might make for an
> interesting discussion. Multiple versions where the only difference
> is your choice of loop control do not. (Or did the book ask for two
> different types of loops?)
>
> --
> Remove del for email
sorry for delay in reply.
here are my answers within the corrected version (I have
solved the issue with the correct exit). as to the versions,
I understand that for this community of high professionals
my "versions" with just one loop change is redundant and not
value adding, but for me it is such a huge step forward in my
understanding; I am getting happy like a kid when I get at least
a tiny result :) I will do my best to follow the rules and not
overload forum with such versions (great that I saw your question,
otherwise I would publish 3 version I did :) ).
// a program that calculates the average of an array of 3 floating-point values; with for loop
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
float values[3];
float element, average;
float sum = 0;
int i, n;
bool is_float;
printf ("Please, enter 3 floating values: \n");
for ( i = 0; i < 3; i++)
{
scanf ("%f", &element);
is_float = 1;
n = (int) element; /*casting allows to check if
the value entered by the user is a float or
an integer; when I turn element into integer,
then (int) element - element tests the entered value*/
if (n - element == 0 || element == 0 ) /*element == 0
allows to skip zero values*/
{
is_float = 0;
printf ("Sorry, invalid input\n");
break; /*another version uses return 1;
thus eliminating final if(is_float)*/
}
else
{
values[i] = element;
sum += values[i];
}
}
if (is_float)
printf ("The average of 3 values is %.2f\n", sum / 3);
/*using 2 decimal points only for aesthetic reasons*/
return 0;
}
[toc] | [prev] | [next] | [standalone]
| From | Barry Schwarz <schwarzb@dqel.com> |
|---|---|
| Date | 2015-08-26 02:27 -0700 |
| Message-ID | <r21rtat1fbpjsu4l4eru2ae1l0j5336eiu@4ax.com> |
| In reply to | #68376 |
On Wed, 26 Aug 2015 01:26:50 -0700 (PDT), Alla _
<modelling.data@gmail.com> wrote:
<snip a ton of obsolete and irrelevant verbiage>
>// a program that calculates the average of an array of 3 floating-point values; with for loop
>
>#include <stdio.h>
>#include <stdbool.h>
>
>int main (void)
>{
> float values[3];
> float element, average;
> float sum = 0;
> int i, n;
> bool is_float;
>
>
> printf ("Please, enter 3 floating values: \n");
>
> for ( i = 0; i < 3; i++)
> {
> scanf ("%f", &element);
>
> is_float = 1;
> n = (int) element; /*casting allows to check if
> the value entered by the user is a float or
> an integer; when I turn element into integer,
> then (int) element - element tests the entered value*/
The cast does no such thing. What happens differently if you delete
the cast?
> if (n - element == 0 || element == 0 ) /*element == 0
> allows to skip zero values*/
If element is 0, the second comparison will never even be evaluated.
Therefore it is completely useless.
WHY is a floating point number with a fractional value of 0 considered
invalid?
> {
> is_float = 0;
> printf ("Sorry, invalid input\n");
> break; /*another version uses return 1;
> thus eliminating final if(is_float)*/
> }
>
> else
> {
> values[i] = element;
> sum += values[i];
> }
> }
> if (is_float)
> printf ("The average of 3 values is %.2f\n", sum / 3);
>/*using 2 decimal points only for aesthetic reasons*/
>
> return 0;
>}
--
Remove del for email
[toc] | [prev] | [next] | [standalone]
| From | Alla _ <modelling.data@gmail.com> |
|---|---|
| Date | 2015-08-26 04:21 -0700 |
| Message-ID | <863bc31e-b8f9-4f8d-8d43-a99cf48cf849@googlegroups.com> |
| In reply to | #68379 |
> > for ( i = 0; i < 3; i++)
> > {
> > scanf ("%f", &element);
> >
> > is_float = 1;
> > n = (int) element; /*casting allows to check if
> > the value entered by the user is a float or
> > an integer; when I turn element into integer,
> > then (int) element - element tests the entered value*/
>
> The cast does no such thing. What happens differently if you delete
> the cast?
Well, as I initialized element as a float, I assumed
that even if the user enters an integer, the compiler
will take it as a float X.XX..
Therefore, when I cast int to the entered variable element
and initialize the result to variable n, then when I deduct
from integer n the float variable element, the result should
be a number with decimal points (then it is a float),
or without decimal points (then it is an integer, i.e.
n - element == 0).
>
> > if (n - element == 0 || element == 0 )
/*element == 0 allows to skip zero values*/
>
> If element is 0, the second comparison will never even be evaluated.
> Therefore it is completely useless.
Now I see it. Thank you.
>
> WHY is a floating point number with a fractional value of 0 considered
> invalid?
Mathematically and scientifically it is a float number, but given my lack of knowledge, I couldn't yet find the way to test both for integers and for floats with zeros after decimal points.
>
> > {
> > is_float = 0;
> > printf ("Sorry, invalid input\n");
> > break; /*another version uses return 1;
> > thus eliminating final if(is_float)*/
> > }
> >
> > else
> > {
> > values[i] = element;
> > sum += values[i];
> > }
> > }
> > if (is_float)
> > printf ("The average of 3 values is %.2f\n", sum / 3);
> >/*using 2 decimal points only for aesthetic reasons*/
> >
> > return 0;
> >}
>
> --
> Remove del for email
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-08-26 12:37 +0100 |
| Message-ID | <87egiq1dri.fsf@bsb.me.uk> |
| In reply to | #68389 |
Alla _ <modelling.data@gmail.com> writes:
>> > for ( i = 0; i < 3; i++)
>> > {
>> > scanf ("%f", &element);
>> >
>> > is_float = 1;
>> > n = (int) element; /*casting allows to check if
>> > the value entered by the user is a float or
>> > an integer; when I turn element into integer,
>> > then (int) element - element tests the entered value*/
>>
>> The cast does no such thing. What happens differently if you delete
>> the cast?
> Well, as I initialized element as a float, I assumed
> that even if the user enters an integer, the compiler
> will take it as a float X.XX..
You mean "declared" not "initialized". Yes, it will always be treated
as a double (one of the floating point types).
> Therefore, when I cast int to the entered variable element
> and initialize the result to variable n,
You've missed Barry's point: "What happens differently if you delete the
cast?". The answer is nothing. The code is identical with and without
the cast. Assigning a double to an int converts the double by throwing
away the fractional part. The cast does exactly the same thing.
> then when I deduct
> from integer n the float variable element, the result should
> be a number with decimal points (then it is a float),
> or without decimal points (then it is an integer, i.e.
> n - element == 0).
>
>>
>> > if (n - element == 0 || element == 0 )
> /*element == 0 allows to skip zero values*/
>>
>> If element is 0, the second comparison will never even be evaluated.
>> Therefore it is completely useless.
>
> Now I see it. Thank you.
>>
>> WHY is a floating point number with a fractional value of 0 considered
>> invalid?
>
> Mathematically and scientifically it is a float number, but given my
> lack of knowledge, I couldn't yet find the way to test both for
> integers and for floats with zeros after decimal points.
This keeps missing the point. Why do you care? The user enters a
number. You add it to the sum. What is there to test?
I am pretty sure that this reflects some misunderstanding about types
and input, but I can't put my finger on it so I can't correct it.
<snip>
--
Ben.
[toc] | [prev] | [next] | [standalone]
| From | Richard Heathfield <rjh@cpax.org.uk> |
|---|---|
| Date | 2015-08-26 13:06 +0100 |
| Message-ID | <oZhDx.314562$fK1.181897@fx36.am4> |
| In reply to | #68389 |
On 26/08/2015 12:21, Alla _ wrote:
>
>> > for ( i = 0; i< 3; i++)
>> > {
>> > scanf ("%f",&element);
>> >
>> > is_float = 1;
>> > n = (int) element; /*casting allows to check if
>> > the value entered by the user is a float or
>> > an integer; when I turn element into integer,
>> > then (int) element - element tests the entered value*/
>>
>> The cast does no such thing. What happens differently if you delete
>> the cast?
> Well, as I initialized element as a float, I assumed
> that even if the user enters an integer, the compiler
> will take it as a float X.XX..
>
> Therefore, when I cast int to the entered variable element
Absolutely the biggest favour you can do yourself when learning C is to
STOP CASTING. Casting is ALMOST ALWAYS WRONG, and the very few times
when it's right are not the times you'd expect.
Whenever you are tempted to cast, resist the temptation. Find a way to
do what you're doing that doesn't require a cast.
Yes, there are some circumstances where a cast is appropriate, but they
are few and far between.
--
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within
[toc] | [prev] | [next] | [standalone]
| From | Bartc <bc@freeuk.com> |
|---|---|
| Date | 2015-08-26 13:43 +0100 |
| Message-ID | <mrkc5q$j7b$1@dont-email.me> |
| In reply to | #68394 |
On 26/08/2015 13:06, Richard Heathfield wrote: > Absolutely the biggest favour you can do yourself when learning C is to > STOP CASTING. Casting is ALMOST ALWAYS WRONG, and the very few times > when it's right are not the times you'd expect. > > Whenever you are tempted to cast, resist the temptation. Find a way to > do what you're doing that doesn't require a cast. > > Yes, there are some circumstances where a cast is appropriate, but they > are few and far between. As in, finding the byte offset between two pointers? Or stepping a pointer by a byte offset. (I expect now you will say there are no conceivable circumstances where that would be necessary.) -- Bartc
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-08-26 14:03 +0100 |
| Message-ID | <87wpwiyzg4.fsf@bsb.me.uk> |
| In reply to | #68400 |
Bartc <bc@freeuk.com> writes: > On 26/08/2015 13:06, Richard Heathfield wrote: > >> Absolutely the biggest favour you can do yourself when learning C is to >> STOP CASTING. Casting is ALMOST ALWAYS WRONG, and the very few times >> when it's right are not the times you'd expect. >> >> Whenever you are tempted to cast, resist the temptation. Find a way to >> do what you're doing that doesn't require a cast. >> >> Yes, there are some circumstances where a cast is appropriate, but they >> are few and far between. > > As in, finding the byte offset between two pointers? Or stepping a > pointer by a byte offset. You can often do that without casts like this (p2 - p1) * sizeof *p1 but I agree that people often prefer to cast to char * (and you may have to, often because the program is a mess of un-typed pointers already[1]). There are odd corner cases where casts *must* be used. Ironically some of these (a non-void * pointer argument to printf for example) are cases where casts are most often omitted! <snip> [1] By which I mean void *. Yes, I know that is, technically, a typed pointer! -- Ben.
[toc] | [prev] | [next] | [standalone]
| From | Richard Heathfield <rjh@cpax.org.uk> |
|---|---|
| Date | 2015-08-26 14:06 +0100 |
| Message-ID | <1RiDx.478337$cf5.156688@fx08.am4> |
| In reply to | #68400 |
On 26/08/2015 13:43, Bartc wrote:
> On 26/08/2015 13:06, Richard Heathfield wrote:
>
>> Absolutely the biggest favour you can do yourself when learning C is to
>> STOP CASTING. Casting is ALMOST ALWAYS WRONG, and the very few times
>> when it's right are not the times you'd expect.
>>
>> Whenever you are tempted to cast, resist the temptation. Find a way to
>> do what you're doing that doesn't require a cast.
>>
>> Yes, there are some circumstances where a cast is appropriate, but they
>> are few and far between.
>
> As in, finding the byte offset between two pointers?
If the two pointers are of the same type and point into the same object:
long int diff = (pa - pb) * sizeof *pa;
and if they don't, then subtracting one from the other invokes UB.
> Or stepping a
> pointer by a byte offset.
If it's a pointer to a single-byte type (eg char * or unsigned char *),
this is trivial: ++p
If it's a pointer to void *:
void *p = q;
unsigned char *r = p;
r++;
p = r;
although I'm struggling to think of a good use for that one. Now, you
/could/ do this as follows:
void *p = 1 + (unsigned char *)q;
and some would argue that this is preferable. Personally, I'm not
convinced that the idea is sound. If you're addressing the object as
bytes, you probably want to start at the beginning and go on until you
come to the end, and then stop:
foo_t bar(void *p, size_t n)
{
unsigned char *q = p;
...
}
and no cast is required. Yes, it is possible to envisage circumstances
in which you need the cast, but we're talking about some quite involved
C here, and the OP is just not ready for that sort of stuff.
> (I expect now you will say there are no conceivable circumstances where
> that would be necessary.)
No, I'll say that the advice I gave the OP is sound advice. If he avoids
casts like the plague until such time as he really, genuinely needs
them, he will be a better C programmer for it.
--
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within
[toc] | [prev] | [next] | [standalone]
| From | Tim Rentsch <txr@alumni.caltech.edu> |
|---|---|
| Date | 2015-09-06 15:14 -0700 |
| Message-ID | <kfny4gjp54e.fsf@x-alumni2.alumni.caltech.edu> |
| In reply to | #68407 |
Richard Heathfield <rjh@cpax.org.uk> writes:
> On 26/08/2015 13:43, Bartc wrote:
>> On 26/08/2015 13:06, Richard Heathfield wrote:
>>
>>> Absolutely the biggest favour you can do yourself when learning C is to
>>> STOP CASTING. Casting is ALMOST ALWAYS WRONG, and the very few times
>>> when it's right are not the times you'd expect.
>>>
>>> Whenever you are tempted to cast, resist the temptation. Find a way to
>>> do what you're doing that doesn't require a cast.
>>>
>>> Yes, there are some circumstances where a cast is appropriate, but they
>>> are few and far between.
>>
>> As in, finding the byte offset between two pointers?
>
> If the two pointers are of the same type and point into the same object:
>
> long int diff = (pa - pb) * sizeof *pa;
>
> [snip elaboration]
This isn't exactly right. Consider this:
struct { int x; double d; int y; } foo;
int *pa = &foo.x, *pb = &foo.y;
The pointers pa and pb point into the same object, but
they cannot definedly be subtracted.
Also, there are potential signed/unsigned problems mixing a value
of type ptrdiff_t (the pa - pb part) and a value of type size_t
(the sizeof *pa part). If pa < pb, there is a good chance this
expression gives a wildly wrong value.
[toc] | [prev] | [next] | [standalone]
| From | Keith Thompson <kst-u@mib.org> |
|---|---|
| Date | 2015-08-26 11:38 -0700 |
| Message-ID | <lnmvxdx5d6.fsf@kst-u.example.com> |
| In reply to | #68394 |
Richard Heathfield <rjh@cpax.org.uk> writes:
> On 26/08/2015 12:21, Alla _ wrote:
>>
>>> > for ( i = 0; i< 3; i++)
>>> > {
>>> > scanf ("%f",&element);
>>> >
>>> > is_float = 1;
>>> > n = (int) element; /*casting allows to check if
>>> > the value entered by the user is a float or
>>> > an integer; when I turn element into integer,
>>> > then (int) element - element tests the entered value*/
>>>
>>> The cast does no such thing. What happens differently if you delete
>>> the cast?
>> Well, as I initialized element as a float, I assumed
>> that even if the user enters an integer, the compiler
>> will take it as a float X.XX..
>>
>> Therefore, when I cast int to the entered variable element
>
> Absolutely the biggest favour you can do yourself when learning C is to
> STOP CASTING. Casting is ALMOST ALWAYS WRONG, and the very few times
> when it's right are not the times you'd expect.
>
> Whenever you are tempted to cast, resist the temptation. Find a way to
> do what you're doing that doesn't require a cast.
>
> Yes, there are some circumstances where a cast is appropriate, but they
> are few and far between.
It's also important to understand what a "cast" is, and the
difference between a cast and a conversion. (I don't think Alla
has this problem, but plenty of other people do.)
A *cast* is an operator, consising of a type name in parentheses,
that performs an explicit type conversion. You'll sometimes
see the phrase "implicit cast", but there is no such thing in C.
There are implicit conversions, which is what someone using the
phrase "implicit cast" is usually trying to say.
A *conversion* takes a value of one type and yields a value of a
different type, usually with the same or a similar logical value.
For example converting the double value 2.0 to int yields the int
value 2.
Conversions may be either implicit or explicit. Explicit conversions
are performed using a cast. In well written code, most conversions
are likely to be implicit.
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
[toc] | [prev] | [next] | [standalone]
| From | Keith Thompson <kst-u@mib.org> |
|---|---|
| Date | 2015-08-26 11:44 -0700 |
| Message-ID | <lnio81x52u.fsf@kst-u.example.com> |
| In reply to | #68389 |
Alla _ <modelling.data@gmail.com> writes:
[attribution missing]
>> WHY is a floating point number with a fractional value of 0 considered
>> invalid?
>
> Mathematically and scientifically it is a float number, but given my
> lack of knowledge, I couldn't yet find the way to test both for
> integers and for floats with zeros after decimal points.
Are you trying to distinguish between an input like "2.0" and an input
like "2"?
If you read input into a floating-point object, you'll get exactly the
same value for either input. Once you've done that, you've lost any
information about what the input looked like as a sequence of
characters.
You can, if you like, read the input *as a string*, determine whether it
matches the syntax of a floating-point constant or an integer constant,
and take different action from there, converting the string "2" to an
integer value or the string "2.0" to a floating-point value.
But I'm not at all sure why you'd want to do that. If a program asks
for a floating-point number as input, C's standard *scanf() and strto*()
function accept either "2" and "2.0" as valid input -- and IMHO your
program *should* accept "2" as floating-point input. If you want to
make that distinction, you can, but I don't think yhou should. It
violates the Principle of Least Surprise; I *expect* to be able to type
"2" and have it interpreted as 2.0.
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
[toc] | [prev] | [next] | [standalone]
| From | Barry Schwarz <schwarzb@dqel.com> |
|---|---|
| Date | 2015-08-22 10:49 -0700 |
| Message-ID | <0cdhtad79te0nd94oesptbrgm4j6pjargh@4ax.com> |
| In reply to | #67999 |
On Sat, 22 Aug 2015 03:50:31 -0700 (PDT), Alla _ <modelling.data@gmail.com> wrote: >I am trying to correct my errors in this >program. I try to check if the user enters >a float or an integer. >Again I miss ground understanding: >the compiler yells at me by posting the error >message > In function 'main': > error: invalid operands to binary % >(have 'float' and 'int') When you are asking for help about an error message from the compiler or linker, it is helpful if you provide the full text of the message. If you don't understand the message then if follows you don't know whether something you omitted or paraphrased is significant. You really need to invest in a decent tutorial. Usenet is not an efficient way to learn to program or to learn a programming language. -- Remove del for email
[toc] | [prev] | [next] | [standalone]
| From | Alla _ <modelling.data@gmail.com> |
|---|---|
| Date | 2015-08-22 11:16 -0700 |
| Message-ID | <d0c5c1a7-577e-4edb-a5a1-75734d7a1dad@googlegroups.com> |
| In reply to | #68028 |
On Saturday, August 22, 2015 at 9:49:45 PM UTC+4, Barry Schwarz wrote: > On Sat, 22 Aug 2015 03:50:31 -0700 (PDT), Alla _ > <modelling.data@gmail.com> wrote: > > >I am trying to correct my errors in this > >program. I try to check if the user enters > >a float or an integer. > >Again I miss ground understanding: > >the compiler yells at me by posting the error > >message > > In function 'main': > > error: invalid operands to binary % > >(have 'float' and 'int') > > When you are asking for help about an error message from the compiler > or linker, it is helpful if you provide the full text of the message. > If you don't understand the message then if follows you don't know > whether something you omitted or paraphrased is significant. > > You really need to invest in a decent tutorial. Usenet is not an > efficient way to learn to program or to learn a programming language. > > -- > Remove del for email I am learning using internet resources, as well as Programming in C book. Hope to achieve the desired result. I understand that I can't ask for help on error messages, unless I provide the full text; hence, I am posting complete error message, not omitting anything. (except for the name of the file).
[toc] | [prev] | [next] | [standalone]
| From | Alla _ <modelling.data@gmail.com> |
|---|---|
| Date | 2015-08-29 07:19 -0700 |
| Message-ID | <ec19ca5f-267e-4750-a321-3d3fad72b934@googlegroups.com> |
| In reply to | #67931 |
Thank you Everyone! I have again learned a lot from you.
Still working on this 'simple' program. Here is an improved
version, which still has an important bug:
// a program that calculates the average of an array of 3 floating-point values; with for loop
#include <stdio.h>
int main (void)
{
float values[3];
float element;
float sum = 0;
int i;
printf ("Please, enter 3 floating values: \n");
for ( i = 0; i < 3; i++)
{
if (scanf ("%f", &element) == 1)
{
if (element <= 0)
printf ("Please, enter positive values\n");
i--; /* if I don't decrement i, then the program
will go on 'counting' wrong values and
produce erroneous result; but both i--; and
i -= i do not work; I get an error message (see
below)
else
values[i] = element;
sum += values[i];
}
else
{
printf ("You entered special characters\n");
return;
}
}
printf ("The average of 3 values is %.2f\n", sum / 3);
return 0;
}
Here is the error message I get:
ex6-4.c: In function 'main':
ex6-4.c:21: error: expected expression before 'else'
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-08-29 15:35 +0100 |
| Message-ID | <87egimmabl.fsf@bsb.me.uk> |
| In reply to | #68630 |
Alla _ <modelling.data@gmail.com> writes:
> Thank you Everyone! I have again learned a lot from you.
> Still working on this 'simple' program. Here is an improved
> version, which still has an important bug:
>
> // a program that calculates the average of an array of 3
> floating-point values; with for loop
Only because you put them into an array. The array serves no purpose.
> #include <stdio.h>
>
> int main (void)
> {
> float values[3];
> float element;
> float sum = 0;
> int i;
>
> printf ("Please, enter 3 floating values: \n");
Since you want them to be non-negative the prompt should say so.
> for ( i = 0; i < 3; i++)
> {
> if (scanf ("%f", &element) == 1)
> {
> if (element <= 0)
> printf ("Please, enter positive values\n");
> i--; /* if I don't decrement i, then the program
> will go on 'counting' wrong values and
> produce erroneous result; but both i--; and
> i -= i do not work; I get an error message (see
> below)
> else
> values[i] = element;
> sum += values[i];
You have multiple bugs here. The main one that C is *still* not Python!
C needs {}s to group multiple statements.
A secondary bug is the un-closed comment.
Finally, when you start to fiddle with the for statement's control
variable, stop. That's a big red flag saying "this should not be for
statement". You need a while loop now.
Also, use the array or drop it. It's been there from the start but it
serves no purpose and just makes the program more complex. Why is it
there? Maybe you are supposed to be using it for something...
> }
> else
> {
> printf ("You entered special characters\n");
> return;
> }
> }
>
> printf ("The average of 3 values is %.2f\n", sum / 3);
>
> return 0;
> }
--
Ben.
[toc] | [prev] | [next] | [standalone]
| From | Alla _ <modelling.data@gmail.com> |
|---|---|
| Date | 2015-08-30 02:11 -0700 |
| Message-ID | <225f3e7d-c708-40ec-90f6-b91a57560933@googlegroups.com> |
| In reply to | #68633 |
thank you very much! I was happy to find my errors, right after I posted the version here. Your comments helped me a lot too. It shames me that I did miss those braces. As to arrays, I am using an array because this exercise is part of the chapter on arrays.
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-08-30 12:28 +0100 |
| Message-ID | <87zj19vwvt.fsf@bsb.me.uk> |
| In reply to | #68678 |
Alla _ <modelling.data@gmail.com> writes: > thank you very much! I was happy to find my errors, > right after I posted the version here. Your comments > helped me a lot too. It shames me that I did miss > those braces. The editor I use makes it hard to make that mistake. When I hit tab it adds spaces to the current indentation level as determined by the syntax, and it re-adjusts again when it sees the end of the statement. Things like this and matching brackets just relieve the programmer from some trivialities. > As to arrays, I am using an array because this > exercise is part of the chapter on arrays. Ah. Then I suspect you are doing it wrong. Using an array in a pointless way is unlikely to be what the exercise wants. -- Ben.
[toc] | [prev] | [next] | [standalone]
| From | Keith Thompson <kst-u@mib.org> |
|---|---|
| Date | 2015-08-30 15:02 -0700 |
| Message-ID | <lntwrgtoxj.fsf@kst-u.example.com> |
| In reply to | #68681 |
Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
> Alla _ <modelling.data@gmail.com> writes:
[...]
>> As to arrays, I am using an array because this
>> exercise is part of the chapter on arrays.
>
> Ah. Then I suspect you are doing it wrong. Using an array in a
> pointless way is unlikely to be what the exercise wants.
I disagree. I think the exercise (to compute the average of three
floating-point values using an array) has two parts: to read values
into an array, and to compute the average of the values in an array.
Both are sensible things to do. The fact that the combination
is more easily done without using an array would be relevant in a
real-world program, but not in an introductory exercise.
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
[toc] | [prev] | [next] | [standalone]
Page 2 of 3 — ← Prev page 1 [2] 3 Next page →
Back to top | Article view | comp.lang.c
csiph-web