Ask your own question, for FREE!
Computer Science 14 Online
OpenStudy (anonymous):

How does this code work?? #include int main() { static int n=1; printf("%d ", n) && (n++<100) && main(); return 0; }

OpenStudy (anonymous):

thats the most confusing code ive ever seen (i havent seen much code). && i thought only meant logical and. % is a formatter. not sure how main() calls itself. try http://cplusplus.com/reference/clibrary/cstdio/printf/

OpenStudy (anonymous):

Ok, it's not complex but confusing Here, printf returns the no. char printed so it's always true being used as condition. The second condition (n++<100) is clear. Since main is a int function so it can also be used in a condition, which is used here to call itself until the (n++<100), in confusing manner. The condition formed in first call to main() i.e. when program starts will be - 1 && 1 && 0, then until 100, 2 && 1 && 0, the last on n = 100 3 && 0 && 0, hence here main() is not called as of short-circuiting 3 && 0 is false so the rest of condition (&& main()) is ignored and main is not called again.

OpenStudy (anonymous):

It's important to note that this will not work without the int a being declared static. The static keyword means that the variable's value is maintained between function calls.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!