473,796 Members | 2,648 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this code ANSI-compliant?

I have some code, which I know will not work (I haven't included
<math.h>, so sqrt will be assumed to return an int). What I want to
know is, is an ANSI-compliant implementation required to produce an
executable as output (even if the actual output is undefined)?

#include <stdio.h>
/*#include <math.h>*/

int main()
{
float a=36.0;
a=sqrt(a);
printf("%f; %d; %d; %d",a,sizeof(in t),sizeof(float ),sizeof(double ));
getchar();
return 0;
}

(I use the printf line to see how various implementations treat the
code. I have compiled this code under 4 different implementations ; in
each case, the code runs, but only under gcc has it produced the answer
6.0. In most cases, the compiler interprets the bit-pattern of the
double 6.0 as an int, converts that to a float, and then prints it.)

Thanks in advance.

Jan 23 '06 #1
9 1981
"ais523" <ai****@bham.ac .uk> writes:
I have some code, which I know will not work (I haven't included
<math.h>, so sqrt will be assumed to return an int). What I want to
know is, is an ANSI-compliant implementation required to produce an
executable as output (even if the actual output is undefined)?
No. It's not just the output that's undefined; the *behavior* is
undefined.
#include <stdio.h>
/*#include <math.h>*/

int main()
{
float a=36.0;
a=sqrt(a);
printf("%f; %d; %d; %d",a,sizeof(in t),sizeof(float ),sizeof(double ));
getchar();
return 0;
}


The assignment "a=sqrt(a); " invokes undefined behavior. The standard
says (C99 3.4.3p2):

NOTE Possible undefined behavior ranges from ignoring the
situation completely with unpredictable results, to behaving
during translation or program execution in a documented manner
characteristic of the environment (with or without the issuance of
a diagnostic message), to terminating a translation or execution
(with the issuance of a diagnostic message).

--
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.
Jan 23 '06 #2
Keith Thompson wrote
(in article <ln************ @nuthaus.mib.or g>):
"ais523" <ai****@bham.ac .uk> writes:
I have some code, which I know will not work (I haven't included
<math.h>, so sqrt will be assumed to return an int). What I want to
know is, is an ANSI-compliant implementation required to produce an
executable as output (even if the actual output is undefined)?


No. It's not just the output that's undefined; the *behavior* is
undefined.
#include <stdio.h>
/*#include <math.h>*/

int main()
{
float a=36.0;
a=sqrt(a);
printf("%f; %d; %d; %d",a,sizeof(in t),sizeof(float ),sizeof(double ));
getchar();
return 0;
}


The assignment "a=sqrt(a); " invokes undefined behavior.


Might also mention that sizeof yields a size_t, which may or may
not fit in a %d format specifier on the platform.

Also, math.h shouldn't be commented out.

No newline in the printf().

No reason not to use double instead of float in 2006 either.
--
Randy Howard (2reply remove FOOBAR)
"The power of accurate observation is called cynicism by those
who have not got it." - George Bernard Shaw
How 'bout them Horns?

Jan 23 '06 #3
On 2006-01-23, Keith Thompson <ks***@mib.or g> wrote:
"ais523" <ai****@bham.ac .uk> writes:
I have some code, which I know will not work (I haven't included
<math.h>, so sqrt will be assumed to return an int). What I want to
know is, is an ANSI-compliant implementation required to produce an
executable as output (even if the actual output is undefined)?
No. It's not just the output that's undefined; the *behavior* is
undefined.
#include <stdio.h>
/*#include <math.h>*/

int main()
{
float a=36.0;
a=sqrt(a);
printf("%f; %d; %d; %d",a,sizeof(in t),sizeof(float ),sizeof(double ));
getchar();
return 0;
}


The assignment "a=sqrt(a); " invokes undefined behavior. The standard
says (C99 3.4.3p2):


Actually, the expression sqrt(a) invokes undefined behavior. The
original question, though, was whether this is undefined behavior at
compile-time or at run-time.

NOTE Possible undefined behavior ranges from ignoring the
situation completely with unpredictable results, to behaving
during translation or program execution in a documented manner
characteristic of the environment (with or without the issuance of
a diagnostic message), to terminating a translation or execution
(with the issuance of a diagnostic message).

Jan 23 '06 #4
Randy Howard wrote:

No reason not to use double instead of float in 2006 either.


One reason comes to my mind. Try this:

#include <stdio.h>

double i = 1.7;

int main()
{
printf("%6g\n", ((double)(10.0) *i));
printf("%6d\n", (int)((double)( 10.0)*i));
return 0;
}

Try this on an x86 machine, then on another with IEEE compliant
rounding. This does not happen if you use float variables instead.

On x86:
17
16

On SPARC
17
17
Cheers,
Tom
Jan 23 '06 #5
Thomas Maier-Komor wrote:
Randy Howard wrote:
No reason not to use double instead of float in 2006 either.


One reason comes to my mind. Try this:

#include <stdio.h>

double i = 1.7;

int main()
{
printf("%6g\n", ((double)(10.0) *i));
printf("%6d\n", (int)((double)( 10.0)*i));
return 0;
}

Try this on an x86 machine, then on another with IEEE compliant
rounding. This does not happen if you use float variables instead.

On x86:
17
16


You might want to come and discuss this in comp.lang.asm.x 86

I suspect you'd want to tweak the precision control field and/or the
rounding control field.

<quote>
The default precision is double-extended precision. Selecting double
precision or single precision reduces the size of the significand to 53
bits or 24 bits, respectively, to satisfy the IEEE standard for these
floating-point types. This allows exact replication, on different
IEEE-compliant processors, of calculations done using these
lower-precision data types. When using reduced precision, rounding
clears the unused bits on the right of the significand to 0s.
</quote>

--
Regards, Grumble
Jan 23 '06 #6
Grumble wrote:
Thomas Maier-Komor wrote:
Randy Howard wrote:
No reason not to use double instead of float in 2006 either.

One reason comes to my mind. Try this:

#include <stdio.h>

double i = 1.7;

int main()
{
printf("%6g\n", ((double)(10.0) *i));
printf("%6d\n", (int)((double)( 10.0)*i));
return 0;
}

Try this on an x86 machine, then on another with IEEE compliant
rounding. This does not happen if you use float variables instead.

On x86:
17
16


You might want to come and discuss this in comp.lang.asm.x 86

I suspect you'd want to tweak the precision control field and/or the
rounding control field.

<quote>
The default precision is double-extended precision. Selecting double
precision or single precision reduces the size of the significand to 53
bits or 24 bits, respectively, to satisfy the IEEE standard for these
floating-point types. This allows exact replication, on different
IEEE-compliant processors, of calculations done using these
lower-precision data types. When using reduced precision, rounding
clears the unused bits on the right of the significand to 0s.
</quote>


I don't really discuss workarounds. I just wanted to state that there
are situations that might be a valid reason not to use double.

It is sad, but it is a problem of the x86 processor implementation. Not
all processors are effected from this issue.
BTW: this is one of the most often reported non-bugs of gcc.
Look here: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=323
Cheers,
Tom
Jan 23 '06 #7
Jordan Abel wrote:
On 2006-01-23, Keith Thompson <ks***@mib.or g> wrote:
"ais523" <ai****@bham.ac .uk> writes:
#include <stdio.h>
/*#include <math.h>*/

int main()
{
float a=36.0;
a=sqrt(a);
printf("%f; %d; %d; %d",a,sizeof(in t),sizeof(float ),sizeof(double ));
getchar();
return 0;
}


The assignment "a=sqrt(a); " invokes undefined behavior. The standard
says (C99 3.4.3p2):


Actually, the expression sqrt(a) invokes undefined behavior. The


can you elaborate on what the undefined behavior is? keith's note
doesn't really shed any light. would using sqrtf make it correct?
NOTE Possible undefined behavior ranges from ignoring the
situation completely with unpredictable results, to behaving
during translation or program execution in a documented manner
characteristic of the environment (with or without the issuance of
a diagnostic message), to terminating a translation or execution
(with the issuance of a diagnostic message).


Jan 23 '06 #8
"tedu" <tu@zeitbombe.o rg> writes:
Jordan Abel wrote:
On 2006-01-23, Keith Thompson <ks***@mib.or g> wrote:
> "ais523" <ai****@bham.ac .uk> writes:
>> #include <stdio.h>
>> /*#include <math.h>*/
>>
>> int main()
>> {
>> float a=36.0;
>> a=sqrt(a);
>> printf("%f; %d; %d; %d",a,sizeof(in t),sizeof(float ),sizeof(double ));
>> getchar();
>> return 0;
>> }
>
> The assignment "a=sqrt(a); " invokes undefined behavior. The standard
> says (C99 3.4.3p2):


Actually, the expression sqrt(a) invokes undefined behavior. The


can you elaborate on what the undefined behavior is? keith's note
doesn't really shed any light. would using sqrtf make it correct?
> NOTE Possible undefined behavior ranges from ignoring the
> situation completely with unpredictable results, to behaving
> during translation or program execution in a documented manner
> characteristic of the environment (with or without the issuance of
> a diagnostic message), to terminating a translation or execution
> (with the issuance of a diagnostic message).


The note was to clarify what the standard says about undefined
behavior (that it can result in a compilation failure as well as
arbitrary run-time behavior).

Jordan is right; it's the call itself that invokes undefined behavior.
(My statement that the assignment inovkes undefined behavior was less
precise; I was referring to the expression as a whole, which includes
the call, not to the act of assigning the value.)

The call sqrt(a) invokes undefined behavior because there's no visible
prototype for the sqrt() function. In C90, it's implicitly assumed
that the function takes an unknown number and type(s) of arguments and
returns int. Since the actual sqrt() function returns double, you're
lying to the compiler, and it will get its revenge. The most likely
behavior is that the generated code will grab an int value from
somewhere (either from the location that the actual double result is
stored, or from somewhere else, depending on the calling conventions)
and *assume* that it's an int. That's where the undefined behavior
takes place. If that doesn't blow up, the int value is then
implicitly converted to float and assigned to a. (The same thing
would happen if you replaced sqrt() with fsqrt().)

In C99, implicit int has been removed. I *think* this means that the
call is illegal, since the compiler has no way to guess, even
incorrectly, what the actual return type of sqrt() is -- or it might
just be undefined behavior for subtly different reasons. I'm sure
someone can find chapter and verse to determine exactly what the rules
are.

The proper solution, of course, is to add the proper "#include <math.h>"
so there *is* a prototype in scope.

Worrying about just how the program can behave without the prototype
might arguably be a waste of time, but it can be illuminating, or at
least interesting, in tracking down program bugs, in implementing a
compiler, or just in understanding the rules of the language. The
original question was specifically about the nature of undefined
behavior for an admittedly incorrect program.

--
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.
Jan 23 '06 #9
Thomas Maier-Komor wrote:
Grumble wrote:
Thomas Maier-Komor wrote:
Randy Howard wrote:

No reason not to use double instead of float in 2006 either.

One reason comes to my mind. Try this:

#include <stdio.h>

double i = 1.7;

int main()
{
printf("%6g\n", ((double)(10.0) *i));
printf("%6d\n", (int)((double)( 10.0)*i));
return 0;
}

Try this on an x86 machine, then on another with IEEE compliant
rounding. This does not happen if you use float variables instead.

On x86:
17
16
You might want to come and discuss this in comp.lang.asm.x 86

I suspect you'd want to tweak the precision control field and/or the
rounding control field.

<quote>
The default precision is double-extended precision. Selecting double
precision or single precision reduces the size of the significand to 53
bits or 24 bits, respectively, to satisfy the IEEE standard for these
floating-point types. This allows exact replication, on different
IEEE-compliant processors, of calculations done using these
lower-precision data types. When using reduced precision, rounding
clears the unused bits on the right of the significand to 0s.
</quote>


(Again, we should discuss this in comp.lang.asm.x 86)
I don't really discuss workarounds. I just wanted to state that there
are situations that might be a valid reason not to use double.


<quote the Intel manual>
When the x87 FPU is initialized with either an FINIT/FNINIT or
FSAVE/FNSAVE instruction, the x87 FPU control word is set to 0x37F,
which masks all floating-point exceptions, sets rounding to nearest, and
sets the x87 FPU precision to 64 bits.

[...]

The double precision and single precision settings reduce the size of
the significand to 53 bits and 24 bits, respectively. These settings are
provided to support IEEE Standard 754 and to provide compatibility with
the specifications of certain existing programming languages. Using
these settings nullifies the advantages of the double extended-precision
floating-point format's 64-bit significand length. When reduced
precision is specified, the rounding of the significand value clears the
unused bits on the right to zeros.
</quote>

#include <stdio.h>

void set_FPU_control _word(unsigned int mode)
{
__asm__ ("fldcw %0" : /* no output */ : "m" (mode));
}

double d = 1.7;

int main(void)
{
set_FPU_control _word(0x27f);
printf("%6g\n", ((double)(10.0) *d));
printf("%6d\n", (int)((double)( 10.0)*d));
return 0;
}

On a Pentium MMX, the output is:
17
17

See also:
http://www.network-theory.co.uk/docs...cintro_70.html

--
Regards, Grumble
Jan 25 '06 #10

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

Similar topics

242
13464
by: James Cameron | last post by:
Hi I'm developing a program and the client is worried about future reuse of the code. Say 5, 10, 15 years down the road. This will be a major factor in selecting the development language. Any comments on past experience, research articles, comments on the matter would be much appreciated. I suspect something like C would be the best based on comments I received from the VB news group. Thanks for the help in advance James Cameron
7
4830
by: Skybuck Flying | last post by:
Hi, if (__builtin_expect (!buffer->__init, 0)) { buffer->__a = 0x5deece66dull; buffer->__c = 0xb; buffer->__init = 1; } I am using visual c 6 and this code doesn't compile, it's probably not
4
3753
by: Luke Wu | last post by:
I am just wondering what the following terms usually mean: 1) "Standard C" 2) "K&R C" 3) "ANSI C" I am pretty sure "ANSI C" usually refers to the C89 standard, but what
4
1966
by: Anonymousgoogledeja | last post by:
hi all, while I read the code from linux sources. I read the statement static const struct iw_ioctl_description standard_ioctl = { = { .header_type = IW_HEADER_TYPE_NULL, },
0
3839
by: nygiantswin2005 | last post by:
I am tring to write simple console application in C# to test the APIs functions made available by the dymo sdk. The dymo sdk provides a dll library that can be used to call functions that will print labels on the DYMO LabelWriter printer. Here is my C# code. Please let what am I doing wrong. This code is successfully compiled, but it does not work when you execute the final executable program. I have included the c structure and...
7
5300
by: sandy | last post by:
hello can anbody help me in getting source code for tcp/ip stack in ANSI C or source code for http protocol
7
4857
by: Paul Connolly | last post by:
char *s = "Hello"; s = 'J'; puts(s); might print "Jello" in a pre-ANSI compiler - is the behaviour of this program undefined in any pre-ANSI compiler - or would it always have printed "Jello" with a pre-ANSI compiler? In gcc with the "writable-strings" option this program prints Jello If there were more than one semantics for what this progran did under a
232
13360
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *$ If the...
0
10603
NeoPa
by: NeoPa | last post by:
ANSI-89 v ANSI-92 Before we get into all the various types of pattern matching that can be used, there are two ANSI standards used for the main types of wildcard matching (matching zero or more characters or simply matching a single character) : ANSI-89 - Mainly used only by Jet / ACE SQL ANSI-92 - Mainly used by SQL Server and other grown-up products In the later versions of Access it is now possible to select ANSI-92 compatibility as an...
41
3171
by: jaysome | last post by:
It's been almost eight years since ISO/IEC approved ISO/IEC 9899:1999. Does anyone know if ANSI has approved it? A Google search shows arguably confusing answers as to whether ANSI has approved it. For example, on this site: http://en.wikipedia.org/wiki/C_(programming_language)#ANSI_C_and_ISO_C it says that "It was adopted as an ANSI standard in March 2000."
0
9530
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
10459
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
10236
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
10182
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,...
1
7552
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
6793
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
5445
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...
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.