i read somewhere that
printf takes the values of the first two assignments of the program. Any
number of printf’s may be given. All of them take only the first two
values. If more number of assignments given in the program,then printf
will take garbage values.
i don’t think so but it was given on many websites so just need to confirm it
For example, if you do a simple Google search for "printf takes first two assignment as input" there are sites that have sample interview question/answers such as:
Predict the output or error(s) for the following:
main()
{
int i=400,j=300;
printf("%d..%d");
}
Answer: 400..300
Explanation: printf takes the values of the first two assignments of the program. Any number of printf’s may be given.
All of them take only the first two values. If more number of
assignments given in the program,then printf will take garbage values.
Is this the correct true behavior? or is it implementation dependent?
You can find such Q&A places like:
this puzzle site
and this interview question doc
No, it’s definitely not true.
For the context, read C11 7.21.6.3/2:
So, from the standard, C11 7.21.6.1/2:
(emphasis mine)
What can possibly happen is that the values from the stack may be pulled by
printf()when it’s called. Then again, since behavior is undefined, anything could happen, from printing garbage values or a program crash, to printing out a cake picture on the neighbor’s parallel printer (really, anything).Unless your specific implementation (a specific CPU architecture, with a specific compiler and possibly a specific operating system) documents the specific case as being something you can do, don’t do it.
Your puzzle site’s “puzzles” are mostly a combination of undefined behavior and incorrect assumptions regarding implementation-defined behavior. Some examples are correct, but considering it’s mostly bad, I’d just pretend I never saw it. Random internet sites tend to be a bad resource for learning programming, especially C. If you want to learn C, you should get a proper book on C programming (a list can be found here).