Troubling converting string to long long in C

纵然是瞬间 提交于 2019-12-19 17:36:34

问题


I'm having trouble getting the atoll function to properly set a long long value in c. Here is my example:

#include <stdio.h>

int main(void) {
    char s[30] = { "115" };
    long long t = atoll(s);

    printf("Value is: %lld\n", t);

    return 0;
}

This prints: Value is: 0

This works though:

printf("Value is: %lld\n", atoll(s));

What is going on here?


回答1:


First, let's answer your question:

#include <stdio.h>
#include <stdlib.h>  // THIS IS WHAT YOU ARE MISSING


int main(void) {
    char s[30] = { "115" };
    long long t = atoll(s);

    printf("Value is: %lld\n", t);

    return 0;
}

Then, let's discuss and answer 'why?':

For compatibility with very old C programs (pre-C89), using a function without having declared it first only generates a warning from GCC, not an error (As pointed out by the first comment here, also implicit function declarations are allowed in C89, therefore generating an error would not be appropriate, that is another reason to why only a warning is generated). But the return type of such a function is assumed to be int (not the type specified in stdlib.h for atoll for instance), which is why the program executes unexpectedly but does not generate an error. If you compile with -Wall you will see that:

Warning: Implicit declaration of function atoll

This fact mostly shocks people when they use atof without including stdlib.h, in which case the expected double value is not returned.

NOTE: (As an answer to one of the comments of the question) This is the reason why the results of atoll might be truncated if the correct header is not included.



来源:https://stackoverflow.com/questions/15418262/troubling-converting-string-to-long-long-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!