Note that there are some explanatory texts on larger screens.

plurals
  1. POstrcmp() and strcat() sequence
    text
    copied!<p>On my way to hone my C skills with a C Pointers literature, I came across this code. In this problem, I am supposed to justify the output. I am familiar with working of <code>strcat()</code> and <code>strcmp()</code>. I know that <code>strcmp()</code> returns 0 when the two strings passed, are same. </p> <pre><code># include &lt;stdio.h&gt; # include &lt;string.h&gt; int main() { static char str1[]="Good"; static char str2[20]; static char str3[20] ="Day"; int l; l = strcmp(strcat(str3, strcpy(str2, str1)), strcat(str3, "good")); printf("%d\n", l); return 0; } </code></pre> <p>The answer provided there is 0, which means that two calculated strings must be same. I tried to solve the statement in multiple steps. </p> <p>First, tried <code>strcat(str3, strcpy(str2, str1))</code>. 'str2' gets changed to "Good", then <code>strcat()</code> changes <code>str3</code> to `DayGood'. My gcc compiler agrees with me so far.</p> <p>Coming to <code>strcat(str3, "good")</code>, since str3 has been changed to <code>DayGood</code> already, <code>strcat</code> changes <code>str3</code> to <code>DayGoodgood</code>.</p> <p>Again, gcc agress with me. </p> <pre><code>int main() { static char str1[]="Good"; static char str2[20]; static char str3[20] ="Day"; int l; printf("%s\n", strcat(str3, strcpy(str2, str1))); printf("%s\n", strcat(str3, "good")); //l = strcmp(strcat(str3, strcpy(str2, str1)), strcat(str3, "good")); //printf("%d\n", l); return 0; } </code></pre> <p>It produces </p> <pre><code>DayGood DayGoodgood </code></pre> <p>I again tried this variation.</p> <pre><code>int main() { static char str1[]="Good"; static char str2[20]; static char str3[20] ="Day"; int l; printf("%s\n", strcat(str3, "good")); printf("%s\n", strcat(str3, strcpy(str2, str1))); //l = strcmp(strcat(str3, strcpy(str2, str1)), strcat(str3, "good")); //printf("%d\n", l); return 0; } </code></pre> <p>It produces.</p> <pre><code>Daygood DaygoodGood </code></pre> <p>In my both test cases, I get two different strings for comparison. Why is then <code>strcmp()</code> is producing a 0 ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload