left-hand operand of comma has no effect?

2020-03-02 05:17发布

问题:

I'm having some trouble with this warning message, it is implemented within a template container class

int k = 0, l = 0;
    for ( k =(index+1), l=0; k < sizeC, l < (sizeC-index); k++,l++){
        elements[k] = arryCpy[l];
    }
    delete[] arryCpy;

this is the warning i get

cont.h: In member function `void Container<T>::insert(T, int)':
cont.h:99: warning: left-hand operand of comma has no effect
cont.h: In member function `void Container<T>::insert(T, int) [with T = double]':
a5testing.cpp:21:   instantiated from here
cont.h:99: warning: left-hand operand of comma has no effect
cont.h: In member function `void Container<T>::insert(T, int) [with T = std::string]':
a5testing.cpp:28:   instantiated from here
cont.h:99: warning: left-hand operand of comma has no effect
>Exit code: 0

回答1:

The comma expression a,b,c,d,e is similar to

{
  a;
  b;
  c;
  d;
  return e;
}

therefore, k<sizeC, l<(sizeC - index) will only return l < (sizeC - index).

To combine conditionals, use && or ||.

k < sizeC && l < (sizeC-index)  // both must satisfy
k < sizeC || l < (sizeC-index)  // either one is fine.


回答2:

The expression k < sizeC, l < (sizeC-index) only returns the result of the right-hand test. Use && to combine tests:

k < sizeC && l < (sizeC-index)


回答3:

Change to:

for ( k =(index+1), l=0; k < sizeC && l < (sizeC-index); k++,l++){

When you have a comma expression is evaluated the rightmost argument is returned so your:

 k < sizeC, l < (sizeC-index)

expression evaluates to:

 l < (sizeC-index)

and thus misses

 k < sizeC

use the && to combine the conditions instead.