About fallback in C ++

Sorry for this newbie question, but I can't find on google what I need to know.

I understand the return, but I do not understand it ... What does this mean?

  return (tail+1)%N == head%N;


Thanks a lot for your patience.


source to share

6 answers

It returns true

or false

, depending on whether the expression is true or not.

This is the same as:

if ( (tail+1)%N == head%N )
   return true;
   return false;





(tail + 1)% N == head% N

returns a boolean value, true or false. This statement means that after adding 1 to the trail (trail + 1), and the remainder obtained after dividing with N is equal to the remainder of the head divided by N.% is used to divide with the remainder

(%). Modulo is an operation that gives the remainder of two values.

Check this link for C ++ operators: http://www.cplusplus.com/doc/tutorial/operators/



you are returning boolean. The value represents whether the remainder (tail + 1) divided by N is the same as that of the head.



It evaluates the expression and returns the result. In this case, two operations are compared modulo, and the result will be either true

or false

that will be returned.



returns true if the remainder of division for tail + 1 and head are the same

e.g. if tail is 2, head is 1 and N is 2

(tail + 1)% N equals 1

head% N is also 1

so the whole expression returns true



The short answer is:

Because of the operator, ==

your function will return a value bool

, which means it can only be true

or false

. The equivalent would be something like this:

return 5 == 4;


which will return false

since 5 is not equal to 4.

Long answer:

Instead of writing this on one line, you can split it into multiple lines of code. Suppose that tail

, head

and N

are integer values, then you can write it as follows:

int x, y;
x = (tail+1)%N;
y = head%N;
if ( x == y )
    return true;
    return false;


Now in this code there may also be, which %

confuses you a little. %

called Modulus Operator

and can give you the rest of the arithmetic operations. In a simple example, this would mean:

10 % 3 = 1

because it 10/3

equals 3 with a remainder of 1. So to make it clearer, let's just do another example with your specific problem:

Suppose that tail=10

, head=6

and N=2

. Then you get something like this:

x = (10+1)%2
x = 11 % 2
x = 1

y = 6 % 2
y = 0

y != x


This will return the false

reason x

and are y

not equal. (If you run your code with the given example values)

To learn more about Modulus

, you can take a look here or just on any other basic C ++ tutorial.



All Articles