Question:
How can I maintain variables over different functions in C (basic)?
Another Guy
2011-04-29 22:11:34 UTC
In C (basic) I have two void functions. In the first function I scanf for the user to input an integer. I would like to use this integer in the second void, but I get the error "is used uninitialized in this function". I understand this may be because the variable is not constant over the two functions. Is there a way to get around this?

Thank you!
Three answers:
The Phlebob
2011-04-29 22:25:30 UTC
Define the variable in the function that calls both functions, then pass it to them in their calling sequences. Make sure to pass it by reference (a pointer) to the one that reads it in so it can be returned to the caller. Passing by reference to the second one may or may not be needed.



The alternative, declaring the variable as a global variable, is strongly deprecated. Global variables should be minimized if not avoided altogether, and using the calling sequence as the transfer mechanism allows the functions to be reused for other variables if that becomes necessary.



Hope that helps.
2011-04-30 13:52:56 UTC
Declare it as static, global, or pass a pointer to the string to the function.
Vaibhav
2011-04-30 09:55:58 UTC
well declare it static

or globally

whatever you want


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...