Search code examples
pseudocode

How does this pseudo code is false (does not output 43)


I am studying Software System Development A-Level with Cea. The code is displayed below. The mark scheme says that the pseudo code is false, can someone please explain why that is?

Pseudo Code:

The output from the following pseudo code is 43.
(method) – void incrementNum( int numParam ){
 numParam++
}
(main method) – void main(){
int numArg = 42
incrementNum( numArg )
output numArg // writes 43
}

Solution

  • Have a look into function evaluation strategies, in particular Call by Value. The function incrementNum receives a copy of numArg called numParam, which is increased. The original variable is untouched. Depending on the actual programming language, you have multiple solutions:

    • rewrite incrementNum such that it returns its argument (see cybermonkey's solution)
    • use a different evaluation strategy. e.g. in C++ you can call by reference (note the int& vs int in the signature of increase):
    #include <iostream>
    
    void increase(int& v) {
      v++;
    }
    
    int main() {
      int i = 42;
      increase(i);
      std::cout << i << std::endl;
    
      return 0;
    }
    

    outputs 43.