473,398 Members | 2,403 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,398 software developers and data experts.

what's wrong with atof() and casting?

XZ
Hi everyone, this is really confusing to me:

#include <stdio.h>
main(int argc, char **argv) {
printf("argv[1] = %f\n",(double)atof(argv[1]));
printf("argv[1] = %d\n\n",atoi(argv[1]));
}

$ a.out a
argv[1] = 97.000000
argv[1] = 0

$ a.out 3
argv[1] = 0.000000
argv[1] = 3

Without explicit casting, the first printf() always gives 0.0.

Could anyone help me understand what's wrong with the code?

Thank you for your time,
Steve
Nov 15 '05 #1
15 13012
On Tue, 28 Jun 2005 23:57:12 -0500, XZ <zh***@ews.uiuc.edu> wrote in
comp.lang.c:
Hi everyone, this is really confusing to me:

#include <stdio.h>
main(int argc, char **argv) {
printf("argv[1] = %f\n",(double)atof(argv[1]));
printf("argv[1] = %d\n\n",atoi(argv[1]));
}

$ a.out a
argv[1] = 97.000000
The output above is wrong, of course.
argv[1] = 0

$ a.out 3
argv[1] = 0.000000
argv[1] = 3

Without explicit casting, the first printf() always gives 0.0.

Could anyone help me understand what's wrong with the code?

Thank you for your time,
Steve


Your program invokes undefined behavior. You do not have a prototype
in scope for atof(). You need to include <stdlib.h>.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 15 '05 #2
Hello, Jack!
You wrote on Wed, 29 Jun 2005 00:51:45 -0500:

??>> Could anyone help me understand what's wrong with the code?
??>>
??>> Thank you for your time,
??>> Steve

JK> Your program invokes undefined behavior. You do not have a prototype
JK> in scope for atof(). You need to include <stdlib.h>.
Why is compilation and linking of code successful even without including
stdlib.h? At least linking error should arise, no ?

With best regards, Roman Mashak. E-mail: mr*@tusur.ru
Nov 15 '05 #3
On Wed, 29 Jun 2005 15:11:18 +0900, "Roman Mashak" <mr*@tusur.ru>
wrote in comp.lang.c:
Hello, Jack!
You wrote on Wed, 29 Jun 2005 00:51:45 -0500:

??>> Could anyone help me understand what's wrong with the code?
??>>
??>> Thank you for your time,
??>> Steve

JK> Your program invokes undefined behavior. You do not have a prototype
JK> in scope for atof(). You need to include <stdlib.h>.
Why is compilation and linking of code successful even without including
stdlib.h? At least linking error should arise, no ?


Prior to the 1999 update to the C language standard, it was allowed to
call a function without any sort of declaration or prototype in scope.

This would be defined behavior and work properly if and only if
certain conditions were met:

1. The return type of the function was int (true for atoi(), but NOT
true for atof()).

2. The function took a fixed number and type of arguments (that is,
not like printf() that takes variable arguments.

3. The arguments were all the types produced by default promotion
(that is, not char or short or float).

4. In your call of the function, the arguments you passed were the
correct number and type (after default promotion).

So when you call atoi(argv[1]), the compiler generates a call to a
function returning an int and accepting one char * parameter. This is
the correct type for atoi(), so the call works.

Then you call atof(argv[1]), the compiler generates a call to a
function returning an int and accepting one char * parameter. Since
atof() DOES NOT return an int, this is wrong and undefined behavior.

Note that a compiler is not required to do anything at all when you
generate undefined behavior. Since there is a function with that
name, it links. Some C compilers use an object file format where they
can detect a mis-match in return types when linking, others do not.
There is no requirement in the C standard that they do.

Note that under the 1999 and later versions of the C standard, this
"implicit declaration of function returning int" has been removed from
the language. A compiler conforming to the later standard versions
would be required to issue a diagnostic for this, but that still does
not prevent it from trying to produce a program.

Finally, every compiler I have ever used has an option to generate
some sort of message when you call a function without a prototype,
even prior to C99 where this was not actually a constraint violation.
You should consult your compiler's documentation to see how to enable
such warnings.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 15 '05 #4
Hello, Jack!
You wrote on Wed, 29 Jun 2005 01:52:19 -0500:

??>> Why is compilation and linking of code successful even without
??>> including stdlib.h? At least linking error should arise, no ?

JK> Prior to the 1999 update to the C language standard, it was allowed to
JK> call a function without any sort of declaration or prototype in scope.
[skip]

Moreover, atoi() and atof() are both defined in stdlib.h but only #include
<stdio.h> is put in the source code. Why does compilation succeed anyway?

With best regards, Roman Mashak. E-mail: mr*@tusur.ru
Nov 15 '05 #5
Infact for me I got some surprising results.
Following is the piece of code which I compiled using gcc :-

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char** argv)
{

int iv = atoi(argv[1]);
double dv = atof(argv[1]);
printf("%f %d \n",dv,iv);
return 0;
}

I found that when I give a.out a it gives me 0.000000 and 0
If i give a.out 3 it gives me
3.000000 and 3
This is certainly an unpredictable behaviour

Nov 15 '05 #6
On 2005-06-29 06:04:35 -0400, "Rajan" <rs*******@yahoo.com> said:
Infact for me I got some surprising results.
Following is the piece of code which I compiled using gcc :-

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char** argv)
{

int iv = atoi(argv[1]);
double dv = atof(argv[1]);
printf("%f %d \n",dv,iv);
return 0;
}

I found that when I give a.out a it gives me 0.000000 and 0
If i give a.out 3 it gives me
3.000000 and 3
This is certainly an unpredictable behaviour


What's unpredictable about that? Both functions are doing exactly what
they're supposed to do. They are attempting to convert the given string
to an int or double respectively, and when they fail to do so, they are
returning zero.

--
Clark S. Cox, III
cl*******@gmail.com

Nov 15 '05 #7
Roman Mashak wrote:
Hello, Jack!
You wrote on Wed, 29 Jun 2005 01:52:19 -0500:

??>> Why is compilation and linking of code successful even without
??>> including stdlib.h? At least linking error should arise, no ?

JK> Prior to the 1999 update to the C language standard, it was allowed to
JK> call a function without any sort of declaration or prototype in scope.
[skip]

Moreover, atoi() and atof() are both defined in stdlib.h but only #include
<stdio.h> is put in the source code. Why does compilation succeed anyway?


It compiles because, as Jack stated, the C language prior to C 99 ALLOWS
you to call a function without a prototype in scope.

What you might not have realised is stdlib.h does not include the
definition of atoi, it only includes a prototype to tell the compiler
what the interface is. The actual function is defined in the C library
which your system is automatically linking in.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #8
Rajan wrote:
Infact for me I got some surprising results.
Following is the piece of code which I compiled using gcc :-

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char** argv)
{

int iv = atoi(argv[1]);
double dv = atof(argv[1]);
printf("%f %d \n",dv,iv);
return 0;
}

I found that when I give a.out a it gives me 0.000000 and 0
If i give a.out 3 it gives me
3.000000 and 3
This is certainly an unpredictable behaviour


I don't find it unpredictable at all since the last time I checked "a"
was not a valid decimal digit. So atoi and atof return 0 because the
string was not a valid textual representation of a number.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #9
XZ
Jack Klein wrote:
On Wed, 29 Jun 2005 15:11:18 +0900, "Roman Mashak" <mr*@tusur.ru>
wrote in comp.lang.c:

Hello, Jack!
You wrote on Wed, 29 Jun 2005 00:51:45 -0500:

??>> Could anyone help me understand what's wrong with the code?
??>>
??>> Thank you for your time,
??>> Steve

JK> Your program invokes undefined behavior. You do not have a prototype
JK> in scope for atof(). You need to include <stdlib.h>.
Why is compilation and linking of code successful even without including
stdlib.h? At least linking error should arise, no ?

Prior to the 1999 update to the C language standard, it was allowed to
call a function without any sort of declaration or prototype in scope.

This would be defined behavior and work properly if and only if
certain conditions were met:

1. The return type of the function was int (true for atoi(), but NOT
true for atof()).

2. The function took a fixed number and type of arguments (that is,
not like printf() that takes variable arguments.

3. The arguments were all the types produced by default promotion
(that is, not char or short or float).

4. In your call of the function, the arguments you passed were the
correct number and type (after default promotion).

So when you call atoi(argv[1]), the compiler generates a call to a
function returning an int and accepting one char * parameter. This is
the correct type for atoi(), so the call works.

Then you call atof(argv[1]), the compiler generates a call to a
function returning an int and accepting one char * parameter. Since
atof() DOES NOT return an int, this is wrong and undefined behavior.

Note that a compiler is not required to do anything at all when you
generate undefined behavior. Since there is a function with that
name, it links. Some C compilers use an object file format where they
can detect a mis-match in return types when linking, others do not.
There is no requirement in the C standard that they do.

Note that under the 1999 and later versions of the C standard, this
"implicit declaration of function returning int" has been removed from
the language. A compiler conforming to the later standard versions
would be required to issue a diagnostic for this, but that still does
not prevent it from trying to produce a program.

Finally, every compiler I have ever used has an option to generate
some sort of message when you call a function without a prototype,
even prior to C99 where this was not actually a constraint violation.
You should consult your compiler's documentation to see how to enable
such warnings.

Very clear explanation. Thanks Jack!
I'm actually using gcc 3.3.3. Isn't it supposed to comply with the 1999
standard by default? Or do I have to consult a user's manual even for
compiling such simple code?

Thanks,
Steve
Nov 15 '05 #10
XZ wrote on 29/06/05 :
#include <stdio.h>
main(int argc, char **argv) {
printf("argv[1] = %f\n",(double)atof(argv[1]));
}

$ a.out a
argv[1] = 97.000000

"a" is not a valid floating point text représentation. The behaviour is
undefined. Use strtod().

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

I once asked an expert COBOL programmer, how to
declare local variables in COBOL, the reply was:
"what is a local variable?"

Nov 15 '05 #11
Hello, Flash!
You wrote on Wed, 29 Jun 2005 13:52:20 +0100:

FG> It compiles because, as Jack stated, the C language prior to C 99
FG> ALLOWS you to call a function without a prototype in scope.

FG> What you might not have realised is stdlib.h does not include the
FG> definition of atoi, it only includes a prototype to tell the compiler
FG> what the interface is. The actual function is defined in the C library
FG> which your system is automatically linking in.
Now I see, thanks.
The only one point I missed in Jack Klein's post is:

"The arguments were all the types produced by default promotion (that is,
not char or short or float)."

What's the meaning of default promotion and if so, 'atoi' argument is char ?

With best regards, Roman Mashak. E-mail: mr*@tusur.ru
Nov 15 '05 #12
Flash Gordon wrote:
... the C language prior to C 99 ALLOWS
you to call a function without a prototype in scope.


C99 did not change this.

C99 requires a (mere) function declaration to be in scope when calling
a
named non-veriadic function, but it otherwise allows you to call a non-
variadic function without a prototype. [Note it is UB however if the
promoted arguments do not match the definition parameters.]

--
Peter

Nov 15 '05 #13
On Wed, 29 Jun 2005 14:14:45 -0500, XZ wrote:
I'm actually using gcc 3.3.3. Isn't it supposed to comply with the 1999
standard by default? Or do I have to consult a user's manual even for
compiling such simple code?


GCC's support for ANSI/ISO C99 is continuing to improve. You can check out
the status of any version here: <http://gcc.gnu.org/c99status.html>

GCC 4.0 is likely to better support C99 than GCC 3.4. Likewise GCC 3.4 is
likely to better support C99 than GCC 3.3. The latest CVS version of GCC
is likely to have better support than all released versions.

None of the released versions comply with C99 by default. You must feed
gcc the -std=c99 argument:

$ man gcc-4.0

-std=
Determine the language standard. This option is currently only
supported when compiling C or C++. A value for this option
must be provided; possible values are

c89
iso9899:1990
ISO C90 (same as -ansi).

iso9899:199409
ISO C90 as modified in amendment 1.

c99
c9x
iso9899:1999
iso9899:199x
ISO C99. Note that this standard is not yet fully
supported; see <http://gcc.gnu.org/gcc-4.0/c99status.html>
for more information. The names c9x and iso9899:199x are
deprecated.

gnu89
Default, ISO C90 plus GNU extensions (including some C99
features).

...

Note from above that -std=gnu89 is the current default.

I'd like to see an -std=posix option which would be c99 plus defined
support for casting between pointers to void and pointers to functions.*

Regards,
Adam

*<http://www.opengroup.org/onlinepubs/009695399/functions/dlsym.html>
Nov 15 '05 #14
Jack Klein wrote:
.... snip ...
Finally, every compiler I have ever used has an option to generate
some sort of message when you call a function without a prototype,
even prior to C99 where this was not actually a constraint violation.
You should consult your compiler's documentation to see how to enable
such warnings.


Whenever something of the sort appears here I never seem to notice
the missing #include, because my compiler usage would have warned
me of this, and thus I don't normally bother worrying about it.
The first cycle of "fix the obvious errors" would have cleaned it
out.

--
"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Nov 15 '05 #15
CBFalconer wrote:
Jack Klein wrote:

... snip ...

Finally, every compiler I have ever used has an option to generate ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ some sort of message when you call a function without a prototype,
even prior to C99 where this was not actually a constraint violation.
I can't see this particular post of Jack's on Google, but note that
it is not a contraint violation to call an named by unprototyped
function in C99, although it is a constraint that a named function
be declared when called.
You should consult your compiler's documentation to see how to enable
such warnings.


Whenever something of the sort appears here I never seem to notice
the missing #include, because my compiler usage would have warned
me of this, and thus I don't normally bother worrying about it.
The first cycle of "fix the obvious errors" would have cleaned it
out.


Both of you are ardent protagonists against malloc casting on the
basis that it can hide an error if there is no prototype in scope.
I find it amusing how neither of you (nor other protagonists)
mention such a common, obvious and useful compiler option in the
other specific context.

--
Peter

Nov 15 '05 #16

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

Similar topics

4
by: Sharon | last post by:
hi all what are the reverse functions of atof( ), atoi( ) and atol( ) ? I want to change sth to string thx!
6
by: Sreekanth | last post by:
Hello, Am trying to convert a string to float. Am using atof() for that purpose. But the return value for atof is same for the string "0.0" and for some invalid input "Invalid". Can any body...
13
by: Jason Huang | last post by:
Hi, Would someone explain the following coding more detail for me? What's the ( ) for? CurrentText = (TextBox)e.Item.Cells.Controls; Thanks. Jason
67
by: neilcancer | last post by:
i come from china,and i'm sorry that my english is very poor. now i'm studing data structure and i met some problem about c language. could you tell me what will happen after i use free()? i...
21
by: oksuresh | last post by:
Hi talents, I have noticed that atof() function approximates the string I pass to it. when I use atof() , as atof(" 184.64") and it returns 184.63999999999 But I would like to have...
5
by: tjay | last post by:
Hi. I wrote some code using sprintf and atof to store a double as a string of fixed length and to convert it back to a double variable. The string is stored in a char buffer global variable. I'm...
14
by: sharmaharish | last post by:
I need a conversion function that converts values from string to a particular type. For this I have a template function that looks like this ... template<class T> T value(const string& s) {...
5
by: lcw1964 | last post by:
Greetings again, I will burden the group with yet another tenderfoot question, but since conscientious googling hasn't yield a lucid answer I thought I would risk the shortcut of asking here...
23
by: mahesh | last post by:
Hi all, I have following code that is supposed to increase the power by specified value. int main() { system("cls"); int i, exponent; double base; double new_base=0.0;
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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...

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.