-2
#include <iostream>
using namespace std;
multiplication() {
  int x;
  int y;
  int sum;
  sum = y * x;

  cout << "multiplication" << endl;
  cout << "enter first number for multiplication: ";
  cin >> x;
  cout << "enter second number for multiplication: ";
  cin >> y;
  cout << "your product is: " << sum <<endl;
  return 0;
}
void division (){
  cout << "division" << endl;

}
void addition (){
  int y;
  int x;
  int sum = x * y;
  cin >> x;
  cin >> y;
  cout << sum;
}
void subtraction (){

}

int main()
{cout << "enter 1 for multiplication, enter 2 for division, enter 3 for addition, and enter 4 for subtraction"<<endl;
  int math;
  cin >> math;
  switch(math){

    case 1:
      multiplication();
      break;
    case 2:
      division();

    default:
      cout << "it dont work ooga booga"<<endl;
      break;
    case 3:
      addition ();
      break;
    case 4:
      subtraction();}
  return 0;
}

this is the script i am trying to run, im running in code::blocks if something is wrong that would cause it to always return 466750944 please tell me so i could work more on this, this may be my a problem with codeblocks if someone could also run this script in codeblocks or another ide and post their results it would be very much appreciated, thank you

zzxyz
  • 2,953
  • 1
  • 16
  • 31
canes
  • 11
  • 1
    `multiplication() {` is a syntax error in C++. – melpomene Sep 20 '18 at 22:44
  • Always turn compiler warnings as strict as you can; that will catch all sorts of problems including this one. – o11c Sep 20 '18 at 23:08
  • 1
    `int sum = x * y` does not declare a relationship. It's a statement that executes when it's encountered, and the resulting *value* is assigned to `sum`. Afterwards, `sum` has no knowledge of `x` or `y` and is independent of them. Changing `x` or `y` after the assignment will not change the value of `sum`. – François Andrieux Sep 20 '18 at 23:11
  • Terminology note: [Scripting Language vs Programming Language](https://stackoverflow.com/questions/17253545/scripting-language-vs-programming-language) – user4581301 Sep 20 '18 at 23:27

1 Answers1

6

When you say sum = x * y that is evaluated at the point of definition, it's not a formula as in math where later on it's evaluated when rendered.

When the sum = x * y statement is executed, x and y are not initialized so the value of sum is basically garbage.

To see this behaviour in action, step through your code in a debugger and look at the values of x, y and sum.

Either move that to after x and y are properly defined, or move it to a function, like:

int sum(int x, int y) {
  return x * y;
}
tadman
  • 208,517
  • 23
  • 234
  • 262