From the course: Complete Guide to C Programming Foundations

Unlock the full course today

Join today to access over 24,300 courses taught by industry experts.

Retaining values in a function

Retaining values in a function - C Tutorial

From the course: Complete Guide to C Programming Foundations

Retaining values in a function

- [Instructor] Variables used in a function are discarded when the function exits. You can return the variable's value from the function, but when your code relies upon values remaining in the function, you can get into trouble. In this code, both the main and funct functions use integer variable A. It's not the same variable as its private to each function. Run the code and you see the variable retains its value in the main function and in funct, the value isn't changed because again, they're separate variables. In this code, I desire to have the value of variable A in the funct function be retained. It's declared and initialized to zero here. At line seven, its value is increased by 16. The value is output then returned to the main function. In the main function, the value is also output. The funct function is called three times. My hope is that each time, the value of variable A in the funct function is increased by 16. And it doesn't work. The reason it doesn't work is because the…

Contents