Question

I'm manually calculating the number of cells in a Windows console. (Yes, I know this information is available from a filled CONSOLE_SCREEN_BUFFER_INFO struct.)

#include <windows.h>
#include <stdio.h>

int main(void)
{
    HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    RECT workarea;
    COORD c;

    SystemParametersInfoW(SPI_GETWORKAREA, 0, &workarea, 0);
    printf("Rectangle: %ld x %ld\n", workarea.right, workarea.bottom);
    c.X = workarea.right / 8;
    c.Y = workarea.bottom / 12;
    printf("Cells: %d x %d\n", c.X, c.Y);

    return 0;
}

The RECT workarea is a structure containing four long integers. The COORD c is a structure with two short integers.

When dividing a long integer by an integer (e.g. 8 or 12, as above), is there a problem assigning the resulting constant to a short integer? Visual Studio 2012 produces a compile-time warning as would be expected.

But in testing this particular case, SystemParametersInfoW(SPI_GETWORKAREA, 0, &workarea, 0) only gives RECT workarea the resolution of my desktop minus the taskbar height (e.g. 1680 x 1010 pixels).

These numbers are, of course, well within the short integer range. So, I suppose the question is: is there a potential for data loss in this particular case?

Was it helpful?

Solution

When you divide a long with an int the result will have data type long (the larger of the two). If the result fits in a short then there will be no data loss when assigning the result to a short.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top