Explain Modulo

Hey guys, I am tying to break this piece of code with no luck. This code is part of a program that reads from a file.

1
2
3
4
5
int num_elements = num_lines%5>0 ? num_lines / 5 + 1 : num_lines;
	if (num_lines == -1) 
	{
		exit(1);
	}


Questions

1. Why is the modulo operator % before the numbers? I though modulo was about remainders. The file it is reading from has info in blocks of 5 lines. What kind of math is it doing here? Is it saying that it can only read 5 lines or 0 lines at a time?

2. At the end it says if all is false than execute num_lines and if it's equal to -1 to exit. So does that mean that if the file it is trying to read doesn't exist to exit the program?

Thank you.
Last edited on
Let's assume num_lines is 16, for example.

int num_elements = (16 % 5 > 0) ? (16 / 5 + 1) : 16;
I've encapsulated some terms / expressions with parentheses to make it easier to understand.

The expression (16 % 5 > 0) evaluates to (1 > 0), which is true (because 16 % 5 leaves a remainder of 1, and 1 is greater than 0).

Since that expression evaluated to true, the value of (16 / 5 + 1) gets assigned to num_elements - note the ternary operator. If the expression would have evaluated to false, then 16 (num_lines) would have been assigned to num_elements.

(16 / 5 + 1) evaluates to 4.2, which gets truncated to 4 because num_elements is an integer. This seems really sketchy and looks like an amateur mistake - the truncation doesn't seem deliberate. It's hard to know why it's written this way without more context.

Finally, an if() branch checks to see if num_lines is -1. Presumably, earlier in the code num_lines is assigned the value of -1 if something isn't right - like if the file doesn't exist, etc.
Last edited on
@xismm Thank you! You've helped me out a lot!
Topic archived. No new replies allowed.