Walter
Walter

Reputation: 483

which statment in the while loop will be performed first?

In this sample program,in the while loop which part will be done first(increment,assignment,test condition).

int main()
{

char s[]="lumps,bumps,swollen veins,new pains";
char t[40]={};
char *ss,*tt;
tt=t;
ss=s;
while(*tt++ = *ss++);
printf("%s\n",t);
return 0;
}

The output of the following program is :

lumps,bumps,swollen veins,new pains

Can someone tell me how this program is giving the output and how the while statment is working

if i am correct first the *ss++ will be done so that the ss will point to the value 'u' and then it will assign to *tt++ i.e(t[1]).so if it is like this the output should be "umps,bumps,swollen veins,new pains" . The L should not be printed but why L is also printing

Upvotes: 0

Views: 82

Answers (3)

Chintan Patel
Chintan Patel

Reputation: 320

Its not the way it behaves. As you are using post increment, fisrt of all *ss will get ss[0] from string and assign it in *tt (tt[0]), then pointers will increment and in next iteration ss[1] will be copied into tt[1] and so on. So in tt string, you will get exactly same string as you have in ss

Upvotes: 0

Udbhav Kalra
Udbhav Kalra

Reputation: 87

In the above program, I have written full description of the process.

Please see that below :

enter image description here

Also :

enter image description here

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

You should take into account

1) priorities of the operators; 2) and that the order of evalutions of subexpressions for some operators is unspecified. 3) results of the operations

The priorities of the operators are following

1) postincrement operator ++ 2) dereferencing * 3) assignment

That it would be more clear you could substitute loop

while(*tt++ = *ss++);

for this one

while( *tt = *ss )
{
    ++tt;
    ++ss;
}

The difference between them is that in the second loop tt and ss will not be incremented if *ss assigned to *tt is equalt to the terminating zero '\0'.

And for understanding the last loop in turn can be rewritten as

while( *tt = *ss, *tt != '\0' )
{
    ++tt;
    ++ss;
}

where there is used the comma operator in the condition

All that you should understand is that the value of the postfix ++ operator is the value of its operand before incrementing.

Upvotes: 3

Related Questions