Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if only one string variable is not nullptr in C++

I have three LPCWSTR string variables called A, B, C.

I am assigning them from another function which can sometimes return nullptr if something goes wrong. like this:

A = MyFunc();
B = MyFunc();
C = MyFunc();

Now, for some stuff with those variables, I need to check if only one of these variables is not nullptr(only one of variables is assigned).

I tried to do this myself like:

if ((A == nullptr) && (B == nullptr) && (C <> nullptr)) {}

Any ideas about how to do this are welcome.

like image 660
Blueeyes789 Avatar asked Aug 04 '17 04:08

Blueeyes789


1 Answers

Easy enough to do with:

int numSet = 0;
A = MyFunc(); if (A != nullptr) numSet++;
B = MyFunc(); if (B != nullptr) numSet++;
C = MyFunc(); if (C != nullptr) numSet++;
if (numSet == 1) // only one is set

You could also encapsulate the behaviour with a helper function:

LPCWSTR MyFuncWithCount(int &countSetProperly) {
    LPCWSTR retVal = MyFunc();
    if (retVal != nullptr) countSetProperly++;
    return retVal;
}

int numSet = 0;
A = MyFuncWithCount(numSet);
B = MyFuncWithCount(numSet);
C = MyFuncWithCount(numSet);
if (numSet == 1) // only one is set

Next step up from there would be using a range-based for loop in conjunction with a braced init list, as per the following complete program:

#include <iostream>
#include <vector>

typedef void * LPCWSTR;  // Couldn't be bothered including Windows stuff :-)

int main() {
    // Only set two for test purposes.

    LPCWSTR A = nullptr, B = nullptr, C = nullptr;
    LPCWSTR D = &A,      E = nullptr, F = &A;

    int numSet = 0;
    for (const auto &pointer: {A, B, C, D, E, F})
        if (pointer != nullptr)
            numSet++;

    std::cout << "Count is " << numSet << std::endl;
}

Or you could embrace modern C++ in all its glory by using lambda functions, as per the following:

#include <iostream>
#include <vector>

typedef void * LPCWSTR;  // Couldn't be bothered including Windows stuff :-)

int main() {
    // Only set two for test purposes.

    LPCWSTR A = nullptr, B = nullptr, C = nullptr;
    LPCWSTR D = &A,      E = nullptr, F = &A;

    int numSet = 0;
    [&numSet](const std::vector<LPCWSTR> &pointers) {
        for (const auto &pointer: pointers)
            if (pointer != nullptr)
                numSet++;
    } (std::vector<LPCWSTR>{A,B,C,D,E,F});

    std::cout << "Count is " << numSet << std::endl;
}

That's probably overkill for your particular case however :-)

like image 199
paxdiablo Avatar answered Sep 27 '22 19:09

paxdiablo