newb7777
newb7777

Reputation: 563

In C language, comparing 2 members of a structure

I seem to have trouble with comparing 2 members of a structure. I can see in watch window that the sequence in all logs are 0x000.

This one evaluates AllLogsNotZero to TRUE

for (i=0;(i<(3)&&(!AllLogsNotZero));i++)
   {
       UINT8 j;
       j=i+1;
       UINT16* comp1;
       UINT16* comp2;
       comp1 = (UINT16*) (&Data.log[i].Sequence);
       comp2 = (UINT16*) (&Data.log[j].Sequence);
       if ((Data.log[i].Sequence == Data.log[j].Sequence) == 0)
            AllLogsNotZero=FALSE;
       else
            AllLogsNotZero=TRUE;

This one evaluates AllLogsNotZero to FALSE

for (i=0;(i<(3)&&(!AllLogsNotZero));i++)
   {
       UINT8 j;
       j=i+1;
       UINT16* comp1;
       UINT16* comp2;
       comp1 = (UINT16*) (&Data.log[i].Sequence);
       comp2 = (UINT16*) (&Data.log[j].Sequence);
       if (Data.log[i].Sequence == Data.log[j].Sequence)
            AllLogsNotZero=FALSE;
       else
            AllLogsNotZero=TRUE;

I don't know why.

Upvotes: 0

Views: 90

Answers (3)

newb7777
newb7777

Reputation: 563

for (i=0;(i<(3)&&(!AllLogsNotZero));i++)
   {
       UINT16 Var1 = 0;

       if (Data.log[i].Sequence == Var1)
            AllLogsNotZero=FALSE;
       else
            AllLogsNotZero=TRUE;

This works!!

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753615

I think you're making a mountain out of a molehill. I think the way I'd write the loop using your current variable name is:

bool AllLogsNotZero = true;
for (int i = 0; i < 4; i++)
{
    if (Data.log[i].Sequence == 0)
    {
        AllLogsNotZero = false;
        break;
    }
}
if (AllLogsNotZero)
    …processing option for no zero logs
else
    …processing option for at least one log zero

We can debate whether the loop limit should be 3 or 4 (or some other value); it isn't entirely clear from your code, but you set j to i+1 and use that, and limit i to < 3, so when the code doesn't use i+1, the limit should probably be 4. It would be better to have an enumeration or #define value for the limit — the name would indicate what you're measuring against better than just the number.

The negative in the name (AllLogsNotZero) also makes life harder; avoid that when you can. For example:

bool LogsZero = false;
for (int i = 0; i < 4; i++)
{
    if (Data.log[i].Sequence == 0)
    {
        LogsZero = true;
        break;
    }
}
if (LogsZero)
    …processing option for at least one log zero
else
    …processing option for no zero logs

Upvotes: 3

unalignedmemoryaccess
unalignedmemoryaccess

Reputation: 7441

Look if statements

First check:

//You check if they are the same
if (Data.log[i].Sequence == Data.log[j].Sequence)

Second check

//You check if they are not the same
if ((Data.log[i].Sequence == Data.log[j].Sequence) == 0)

//Can be evaluated as:
if (Data.log[i].Sequence != Data.log[j].Sequence)

Upvotes: 2

Related Questions