void fun()
{
// What goes here?
}
void main()
{
int x = 20;
fun();
x = 10;
printf("%d",x); // Should print 20.
}
This was one of my test question. I was wondering if I should use static int
. Can you please help me?
Join Stack Overflow to learn, share knowledge, and build your career.
I do not condone this practice, and this is a horrible idea. But technically this meets the question's criteria, sort of.
void fun()
{
// Essentially this is a function with an empty body
// And I don't care about () in a macro
// Because this is evil, regardless
#define printf(a, b) (printf)(a, b*2)
}
void main() // I know this is not a valid main() signature
{
int x = 20;
fun();
x = 10;
printf("%d", x);
}
fun()
, since this #define
could be anywhere (before it is used) and still achieve the same result (since preprocessing/macro expansion happens before compilation, i.e., this technically only changes the "logic" in main()
).
– RastaJedi
Jul 2 '16 at 10:53
Standard disclaimers apply.
Approach 1: Create a new x
variable in an inner scope.
void fun()
{
#define fun() { int x
#define printf } printf
}
Approach 2: Define a second variable that changes to 10
so that x
can always be 20
.
void fun()
{
#define x x=20,y
}
main()
in C areint main(void)
andint main(int argc, char **argv)
(or equivalently,int main(int argc, char *argv[])
). The only thing I can think of, and it's probably not what they are after (or maybe it is, but I'm just saying that because it says "in the main function"), is callingprintf("20\n");
and thenexit(0);
infun()
. – RastaJedi Jul 2 '16 at 4:39fun()
, and thenexit()
... Still a silly question to ask in a test. – void_ptr Jul 2 '16 at 4:41x
is being set to10
afterfun()
returns and beforeprintf()
prints. – RastaJedi Jul 2 '16 at 4:44