Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

c++ - Output difference in gcc and turbo C

Why is there a difference in the output produced when the code is compiled using the two compilers gcc and turbo c.

#include <stdio.h>

int main()
{    
    char *p = "I am a string";
    char *q = "I am a string";

    if(p==q)
    {
        printf("Optimized");
    }
    else{
        printf("Change your compiler");
    }
    return 0;
}

I get "Optimized" on gcc and "Change your compiler" on turbo c. Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your questions has been tagged C as well as C++. So I'd answer for both the languages.

[C]

From ISO C99 (Section 6.4.5/6)

It is unspeci?ed whether these arrays are distinct provided their elements have the appropriate values.

That means it is unspecified whether p and q are pointing to the same string literal or not. In case of gcc they both are pointing to "I am a string" (gcc optimizes your code) whereas in turbo c they are not.

Unspeci?ed Behavior: Use of an unspeci?ed value, or other behavior where this International Standard provides two or more possibilities and imposes no further requirements on which is chosen in any instance


[C++]

From ISO C++-98 (Section 2.13.4/2)

Whether all string literals are distinct(that is, are stored in non overlapping objects) is implementation defined.

In C++ your code invokes Implementation defined behaviour.

Implementation-de?ned Behavior: Unspeci?ed Behavior where each implementation documents how the choice is made


Also see this question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...