July 25th, 2012

One way to make sure you pass an array of the correct size

Another entry in the very sporadic series of “very strange code I’ve seen.” The code has been changed to protect the guilty, but the essence has been preserved.

class Store
{
public:
    // Retrieve "count" colors from item "itemId" into "values"
    bool GetItemColors(int itemId, int count, COLORREF *values);
    // Set "count" colors from "values" into item "itemId"
    bool SetItemColors(int itemId, int count, const COLORREF *values);
};
bool CopyUpToFourColors(Store *store1, Store *store2, int itemId, int count)
{
    COLORREF size1[1];
    COLORREF size2[2];
    COLORREF size3[3];
    COLORREF size4[4];
    int *buffer = ((count == 1) ? size1 :
                  ((count == 2) ? size2 :
                  ((count == 3) ? size3 :
                  ((count == 4) ? size4 :
                                  nullptr))));
    if (buffer == nullptr)
        return false;
    if (!store1->GetItemColors(itemId, count, buffer))
        return false;
    if (!store2->SetItemColors(itemId, count, buffer))
        return false;
    return true;
}
Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion is closed.