I'm new to C++ and I am developing an equation in context of the following code:

fprintf(stderr," inp.width*inp.height*ref.width*ref.height %lld -------->", 2*3 * (long long int)sizeof(float));

which prints 24. Why it is always multiplied by 4?

Someone please explain me what (long long int)sizeof(float)) does?

3

Best Answer


sizeof(float) evaluates to the number of bytes used by the compiler to represent an object of type float. The type of the value returned by the sizeof operator is size_t. The preceding (long long int) casts the value of sizeof(float) to the type long long int. It doesn't change the value since the value is just 4 in your compiler, which can be easily represented by long long int.

The purpose of casting to long long int appears to be to allow the use of the format specifier "%lld".

The sizeof operator returns the amount of bytes that the type or the variable/arrays are in memory. For this example sizeof(float) will return 4 bytes as the type float is 4 bytes in memory. So when you do 2*3*(long long int)sizeof(float), it will return 24.

On most architectures, sizeof(float) is always 4.

Casting to (long long int) is necessary to match the format parameter of %lld - the multiplication will automatically convert the result to the largest of the operand types. In this case, since the expected value isn't going to be larger than a regular int can hold, you could have skipped the cast and used %d instead.