std::cout and printf array

501 views Asked by At
    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 ?

2

There are 2 answers

0
Natasha Dutta On BEST ANSWER

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.

0
Barry On

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.