473,387 Members | 1,742 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Using expressions as arguments of printf function

Hello, please explain the output of following simple C program:
Expand|Select|Wrap|Line Numbers
  1. int main( ) 
  2.     int x = 15; 
  3.     printf("\n%d %d %d", x != 15, x = 20, x > 30);
  4.     return 0; 
Output: 1 20 0

I understand the output 20, its just being assigned to x. But am confused about the return value of other two expressions; i.e. x!=15 and x>30. When do we get a 0 and when a 1?
Jan 21 '14 #1

✓ answered by donbock

From the C99 Standard
6.5 Expressions
...
2 Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
Your code violates this rule by modifying x once and reading it, not once, but twice in order to evaluate the two Boolean expressions -- leading to undefined behavior. Undefined behavior is unpredictable and need not be consistent. From the point of view of the C Standard, it would be just as legitimate for this program to reformat your hard drive as to print the output you're seeing.
Avoid undefined behavior!

6 1303
stdq
94 64KB
Hi! x != 15 is false, since x equals 15 (instead of being different than that), so the returned value in that case is 0 (false). The same goes for x > 30. On the other hand, when the expression is true, then you a get a 1.
Jan 21 '14 #2
Hi stdq, please notice x!=15 didn't return a 0, it returned a 1 (true?). That's why I am confused.
Jan 21 '14 #3
stdq
94 64KB
I understand...I don't know the reason, though. I would expect a 0. Maybe someone will provide us with the answer. Sorry I can't be of more help.
Jan 21 '14 #4
donbock
2,426 Expert 2GB
From the C99 Standard
6.5 Expressions
...
2 Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
Your code violates this rule by modifying x once and reading it, not once, but twice in order to evaluate the two Boolean expressions -- leading to undefined behavior. Undefined behavior is unpredictable and need not be consistent. From the point of view of the C Standard, it would be just as legitimate for this program to reformat your hard drive as to print the output you're seeing.
Avoid undefined behavior!
Jan 21 '14 #5
Friends, I have found a convincing answer.
In C, we follow standard calling convention which is based on 2 things-
1. the order in which arguments are passed to a function
2. the cleanup of stack elements former to store formal arguments and local variable.
Using standard calling convention, arguments are passed in right to left order. So initially we have x=15.
Now,(starting from right) x>30 is false, so it returns 0.
Then, x becomes 20, 20 is printed.
Lastly, x(20)!=15, is true and returns non zero value 1.
And these are printed in order 1 20 0
Jan 22 '14 #6
donbock
2,426 Expert 2GB
It is tempting to think you can figure out how your particular compiler handles certain cases of undefined behavior. However, you can never be sure. The behavior may vary with optimization level or with the instructions surrounding the snippet in question. The behavior will certainly vary from compiler to compiler.

I have 35+ years of experience with programming. I cannot emphasize enough that the correct answer to your original question is...
"The program in question exhibits undefined behavior; so nothing it does should come as a surprise."

Don't give in to the temptation to try and predict what the undefined behavior will be. From there, it is a short hop to writing programs that take advantage of your predictions. The result is nonportable code that fails intermittently.

I have given similar advice here and elsewhere.
Jan 22 '14 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Matt Eberts | last post by:
Sorry, bad title. Anyway, is there a way to pass the arguments to an object instantiated via a constructor using the arguments object and have it expanded, so to speak, so that it doesn't appear as...
1
by: George Sakkis | last post by:
Hi all, I have the following two template function definitions: template <typename Container, typename Sepatator> string join(const Container& c, const Sepatator& s) { // ... } template...
2
by: rejeesh | last post by:
Hi, I need a 'wrapper' function for printf. So that anywhere in my program if i call the wrapper function it does the same thing as the regular printf function, but puts a custom message at the...
7
by: sunfiresg | last post by:
During an interview, I am asked to answer a question: Printf is a major formatted output function provided by the standard C library. Printf accepts a formatting string followed by a various...
6
by: Programador | last post by:
I'm getting this error when running this program: Cannot calculate rate using the arguments provided Module Module1 Sub Main() Rate(360, -694.44444444444446, 244274.69178082192) End Sub
10
by: iulian.ilea | last post by:
Hey, I try to explain what is "arguments from function" :) So... if I have a function (i.e. function me($param1, $param2)). It is possible to call me($param1)? Like in JavaScript.
18
by: sam_cit | last post by:
Hi Everyone, int main() { printf("not included stdio.h"); } Yes, i haven't included stdio.h and my compiler would generate a warning and would assume that it would return a int, my question...
19
by: sam_cit | last post by:
Hi Everyone, I have the following custom printf() function in the my program unit and when i execute the program, the actual printf() function is invoked and i get no error, no warning. However...
3
by: tgiri | last post by:
hello, this is gireesh. can u pls give me solution to this question. PLATFORM : C language Q. What are the input arguments passed to the printf() function? actually i found in header...
2
by: vlsidesign | last post by:
Example printf("I have %d cars. \n", 10); Is it more correct to say that the printf function doesn't insert the integer, rather into changes the integer into chars and then inserts it?
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.