C++ — Functions and value parameters
A C++ function can accept integers by value and return the calculated integer to its caller. Changing a value parameter leaves the caller’s original integer intact.
A simple example
Call a function with 2
- Start with Argument 2
- Do this Double the argument
- Result 4
#include <iostream>
int twice(int n) {
return n + n;
}
int main() {
std::cout << twice(2) << '\n';
}
4
Calculate how many boxes an order needs
Pass small integers by value and return the number of boxes. The comparison contributes either zero or one. Keeping printing outside the function lets different callers use the result.
A library ships 17 books in cartons that hold eight. Two cartons take sixteen books, leaving one book that still needs a carton. An order of exactly sixteen needs only two.
Run the example
C++17. Run these commands from the directory containing the example. Use a Unix-style shell.
c++ -std=c++17 lesson.cpp -o lesson
./lesson
#include <iostream>
int boxesNeeded(int items, int capacity) {
return items / capacity + (items % capacity != 0);
}
int main() {
std::cout << boxesNeeded(17, 8) << '\n';
std::cout << boxesNeeded(16, 8) << '\n';
return 0;
}
3 2
The input contract is a nonnegative whole-number item count and a positive box capacity. Seventeen items fill two boxes of eight with one item left over. Sixteen items fill exactly two boxes.
Try it yourself
How many boxes do zero items need?
Check your answer
Zero. The quotient and remainder are both zero. A zero capacity is outside the function’s contract because division by zero is undefined.