Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do c++ programmers use != instead of <

Tags:

c++

In c++ primer, pg 95 the author says that c++ programmers tend to use != in preference of < when writing loops.

for (vector<int>::size_type i = 0; i != 10; ++i) is preferred instead of  for (vector<int>::size_type i = 0; i < 10; ++i)  

I read the same thing in accelerated c++. Can someone explain the rationale behind this

like image 893
ameen Avatar asked Dec 25 '10 19:12

ameen


People also ask

What is the meaning of != In C?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

What does != 0 mean in C?

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. In fact, !! x is a common idiom for forcing a value to be either 0 or 1 (I personally prefer x != 0 , though).

Is equal c++?

C++ Algorithm Function equal() C++ Algorithm equal()function compares the elements in both the containers and returns a true value if all the elements in both the containers are found to be matching. The first range is from [first1,last1) and the second starts from first2.

What does ++ mean in C?

In programming (Java, C, C++, JavaScript etc.), the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1.


2 Answers

When using some kinds of STL iterators (those that aren't random access), you must use !=:

for (map<int,int>::iterator i = a.begin(); i != a.end(); ++i) ... 

However, I don't see any reason to prefer != for well-ordered scalar types as in your example. I would usually prefer < for scalar types and != for all iterator types.

like image 154
Greg Hewgill Avatar answered Oct 05 '22 19:10

Greg Hewgill


It's a habit for generic programming; for example, you can easiely use < with indices, but you cannot use that with all iterator types. A list iterator cannot efficiently implement < - however, != can be implemented for even the simplest of iterator types. Therefore, it is a good habit to always use the most generic comparison - it makes your code more resilient to change.

like image 36
ltjax Avatar answered Oct 05 '22 18:10

ltjax