Newb
Newb

Reputation: 678

C++ Function clarification

Given:

  x = MyFunc(2); 

My understanding:

The variable x is assigned to the function MyFunc(2).

First, MyFunc( ) is called. When it returns, its return value if any, is assigned to x.?

Upvotes: 0

Views: 193

Answers (3)

Khelben
Khelben

Reputation: 6461

No, quite the contrary, you call the function MyFunc over the value 2 and the result is assigned to x

for example

int MyFunc( int number ) {
  return number + 1;
}
int x = MyFunc(2);
int y = MyFunc(1);

x will be 3 (x+1) and y will be 2

With a different function, the returned value will be different, of course

int MyFunc2( int number ) {
  return number - 1;
}
int x = MyFunc2(2);
int y = MyFunc2(1);

x will be 1 and y will be 0

The main point is, you've got to declare the function and decide what it returns according to its params.

Upvotes: 3

Daniel Daranas
Daniel Daranas

Reputation: 22644

This cannot be answered completely without:

  • x's declaration
  • MyFunc's declaration
  • MyFunc's definition

But your sentence "When MyFunc(2) is called it returns the value 2 to x" is wrong. MyFunc is invoked and 2 is passed as the actual parameter value. MyFunc may return anything, which is then assigned to x.

Upvotes: 7

Frank
Frank

Reputation: 10571

No. x is assigned to the evaluated result of MyFunc(2).

The value returned depends on what MyFunc does. It could be anything and does not need to be 2.

Upvotes: 7

Related Questions