-2

Suppose I hae to following:

int &f() {
static int x = 0;
return x;
}
void main() { f() = 5; }

I realize that this function returns a reference to an integer (I have tried to use this Function returning int&).

Does it mean that x will be equal to 5 in this case?

I do not really realize what f() = 5in that...

In addition, what change could it make If would omit 'static' above?. I know that static int is an integer which exist actually before the program exists, but I am not sure it helps me to understand what change would happen.

I am trying to find out the answers for that with using debugger.

DonaldT
  • 103
  • 8
  • Have you tried figuring out the answer to your own question, by yourself, simply by using a debugger to run this program, one statement at a time, and verifying whether or not your hypothesis is correct, that `x` will be set to 5? Your debugger should be able to easily tell you this, in just a few seconds. This will be actually an excellent way for you to learn how to use a debugger. Being able to effectively use a debugger is a required skill for every C++ developer, and you can use this as an opportunity to get a jump start on learning this valuable skill. – Sam Varshavchik Feb 25 '19 at 01:09

1 Answers1

2

Does it mean that x will be equal to 5 in this case?

Yes. After an integer has been assigned a value, it will be equal to that value.

what change could it make If would omit 'static' above?

Depends on how you intend the program to behave. Only removing static would make the program to have undefined behaviour, so that would not be a good idea. One possible change would be to remove the entire function declaration, and the call to it.

eerorika
  • 232,697
  • 12
  • 197
  • 326