In C++, am I paying for what I am not eating?

后端 未结 13 2010
既然无缘
既然无缘 2020-12-12 12:39

Let\'s consider the following hello world examples in C and C++:

main.c

#include 

int main()
{
    printf(\"Hello world\\n\");
    r         


        
13条回答
  •  再見小時候
    2020-12-12 12:54

    You are not comparing C and C++. You are comparing printf and std::cout, which are capable of different things (locales, stateful formatting, etc).

    Try to use the following code for comparison. Godbolt generates the same assembly for both files (tested with gcc 8.2, -O3).

    main.c:

    #include 
    
    int main()
    {
        int arr[6] = {1, 2, 3, 4, 5, 6};
        for (int i = 0; i < 6; ++i)
        {
            printf("%d\n", arr[i]);
        }
        return 0;
    }
    

    main.cpp:

    #include 
    #include 
    
    int main()
    {
        std::array arr {1, 2, 3, 4, 5, 6};
        for (auto x : arr)
        {
            std::printf("%d\n", x);
        }
    }
    

提交回复
热议问题