473,804 Members | 3,138 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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)a tof(argv[1]));
printf("argv[1] = %d\n\n",atoi(ar gv[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 13085
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)a tof(argv[1]));
printf("argv[1] = %d\n\n",atoi(ar gv[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.l earn.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.l earn.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*******@yaho o.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

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

Similar topics

4
20255
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
4495
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 suggest me the way to differentiate an invalid float number string and a 0.0. TIA, Sreekanth.
13
5063
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
3816
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 mean once i use free() on a pointer,what will the pointer points to ? for example: #include<stdio.h>
21
8368
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 the exact value that is passed.
5
3203
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 afraid it might contain bugs though. If I serialize a double, I get a string of the format "-1.0000000000000000e+212". This string gets stored in the buffer. Then, to convert it back into a double, I pass it to the atof function. The problem...
14
8919
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) { istringstream(s); T val; is >val;
5
6557
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 since I am so very keen to learn to code in standard C. Could someone tell me the long double equivalent of atof()? I was getting some peculiar behaviour in a little bit of math code I am working with. I thought the problem was in the math...
23
4871
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
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
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,...
1
10319
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
7616
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
6851
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
5520
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4297
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3816
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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

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