简体   繁体   中英

std::cout and printf array

    int arrSize = 10;
    double* arr = new double [arrSize];
    for(int i = 0; i < arrSize; i++){
        arr[i] = i;
    }
    for(int i = 0; i < arrSize; i++){       
        printf("%d", arr[i]);
        //std::cout<<arr[i];
    }

Here

  • printf() prints 0000000000.
  • cout prints 0123456789.

Why ?

Using a wrong format specifier for any particular argument in printf() invokes undefined behaviour .

arr is a double array, hence arr[i] produces a double type value. you need %f format specifier to print that. If you use %d to print a double , your program faces UB and the result cannot be justified, in can be anything .

OTOH, the << used with cout is an overloaded operator which can adapt based on the type of the supplied variable. So, it prints the output as expected.

arr[i] is a double , but %d is the format specifier for int . It is undefined behavior to use the wrong format specifier. From the C11 standard, 7.21.6.1/9:

If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

There are lots of format specifiers for double that will format the output in different ways, see this reference for a full list.

On the other hand, operator<< for cout has an overload that takes a double directly (#5 in the linked reference), so that just works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM