473,463 Members | 1,350 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to answer Printf Interview question

One of the recent interview I have been asked to give the output of following program:

Expand|Select|Wrap|Line Numbers
  1. void main()
  2. {
  3.  int i = 5;
  4.  printf(" %d %d %d %d ", ++i,i++,--i,++i);
  5. }
Result is : 7 5 7 7.

I couldnt answer correctly but I dont know how it gets to 7 5 7 7, what is the logic does printf flows to print the above values of i.
May 26 '10 #1
9 3524
Banfa
9,065 Expert Mod 8TB
main returns void, this is undefined behaviour.

If main returned int then this would still exhibit undefined behaviour because of this clause in the standard

""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 accessed only to determine the value to be stored."

anything breaking this clause is undefined behaviour and this code does break it because it tries to modify i 4 times between sequence points.

Since the behaviour is undefined the output can be anything.

On a related point it should be noted that the order of evaluation of parameters to a function is platform dependent.


So the standard correct answer to the question is "anything"
May 26 '10 #2
donbock
2,426 Expert 2GB
The result probably corresponds to one of the 24 permutations of the four arguments. However, the Standard allows a compiler to do anything when a program triggers undefined behavior: blank the screen, reformat your hard drive, blow up an offshore oil well, remove all the ozone from the atmosphere, change Pluto back into a planet, throw the Sun into a black hole, ... it is all fair game.

I hope this explains why Banfa is always so adamant that undefined behavior be avoided.
May 26 '10 #3
As I understand it, the following should be well defined:
Expand|Select|Wrap|Line Numbers
  1. void main()
  2. {
  3.  int i = 5;
  4.  printf(" %d ", ++i);
  5.  printf(" %d ", i++);
  6.  printf(" %d ", --i);
  7.  printf(" %d ", ++i);
  8. }
  9.  
However, would there be a better way of doing this? Maybe this way?:
Expand|Select|Wrap|Line Numbers
  1. void main()
  2. {
  3.  int i = 5;
  4.  int j = ++i;
  5.  int k = i++;
  6.  int l = --i;
  7.  int m = ++i;
  8.  printf(" %d %d %d %d ", j,k,l,m);
  9. }
  10.  
Jun 1 '10 #4
donbock
2,426 Expert 2GB
I agree -- your first code snippet does not invoke any undefined behavior, so its output is predictable.

I can't think of any good reason to prefer one code snippet over the other. I suppose the first snippet is marginally better because you might fool yourself if the order of variables in the printf wasn't the same as the order the variables were assigned. That is, the second snippet presents the possibility that you type something like this:
Expand|Select|Wrap|Line Numbers
  1. void main() 
  2.  int i = 5; 
  3.  int j = ++i; 
  4.  int k = i++; 
  5.  int l = --i; 
  6.  int m = ++i; 
  7.  printf(" %d %d %d %d ", k,j,l,m); 
Jun 1 '10 #5
My intentions were to avoid multiple printf calls. I don't understand why, but I have been told in the past that system calls should always be reduced to as few as possible.
Jun 1 '10 #6
donbock
2,426 Expert 2GB
... as few as possible, but no fewer.
Jun 1 '10 #7
Banfa
9,065 Expert Mod 8TB
To paraphrase Mr Albert Einstein
Jun 2 '10 #8
Banfa
9,065 Expert Mod 8TB
P.S. system calls can take a while to execute because you have to access the system and because you may have to wait for someone else to finish accessing the same system.

So reducing the number of system calls, in theory, makes the program more efficient.
Jun 2 '10 #9
donbock
2,426 Expert 2GB
By the way, another way to get unpredictable results is to access a volatile variable more than once in a single statement.

I once worked with an input device that provided a 32-bit data word via a 16-bit data bus. The first read gave the upper word and the second read was the lower word. My first effort was:
Expand|Select|Wrap|Line Numbers
  1. const unsigned short * const pDevice = <some address>;
  2. ...
  3. unsigned long value;
  4. value = (((unsigned long)*pDevice) << 16) | *pDevice;
Unfortunately for me, this code appeared to work fine. Fortunately I always pass my code through a static checker. It warned me that I had relied on implementation-specific behavior -- that is, I had assumed the left-most pointer dereference happened first. I changed my code to this:
Expand|Select|Wrap|Line Numbers
  1. const unsigned short * const pDevice = <some address>;
  2. ...
  3. unsigned long value;
  4. value = ((unsigned long)*pDevice) << 16;
  5. value |= *pDevice;
Jun 2 '10 #10

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

Similar topics

9
by: Wenjie | last post by:
Hello, Is printf("%d", var); OK for the unsigned long var = SOME_VAR? Or should some other print format be specified? Thanks and best regards, Wenjie
11
by: anonymous | last post by:
Hi CLCers, The program below prints some number and i dont understand why it is behaving like this. I am not supplying the necessary arguments to the printf function and according to my...
12
by: drM | last post by:
I have looked at the faq and queried the archives, but cannot seem to be able to get this to work. It's the usual factorial recursive function, but that is not the problem. It hangs after the user...
15
by: praeiji | last post by:
Hi, I was wondering something today. The following code : unsigned char a = 200; char b = 200; printf( "%d %d", a, b ); gives :
4
by: Mandragon03 | last post by:
I am looking for a way to take a floating point number and get rid of any extraneous 0's at the end. For instance if I have myFloat = 9999; printf("%f", myFloat); I get 9999.0000. I want to...
1
by: Scott McFadden | last post by:
Is there much overhead leaving in printf calls for a release build of my NT service (VC8)? This app runs as a NT service or console app so it's nice to have the console ouput when troublshooting...
4
by: bobm2005 | last post by:
Whatever format I try in Printf, an 'E' format number nearly always has a leading non-zero:- 1.2345E7 -9.3456E8 etc. Is it possible to force it (printf) always to have leading zero? ...
3
by: Bint | last post by:
Hi, I have a giant string buffer, and I want to print out small chunks of it at a time. How do I print out, say 20 characters of a string? Is it like this? printf("%20s",mystring); I...
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...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.