C program of interesting behavior

I came across a piece of code that generates some interesting results when debugging another program.

I created a small program to illustrate this behavior:

#include <stdio.h> int main() { char* word = "foobar"; int i, iterator = 0; for (i = 0; i < 6; i++ && iterator++) printf("%c", word[iterator]); return 0; } 

I know this is the wrong way to print a string. This is for demonstration purposes only.

Here I expected the output to be "foobar", obviously, but instead it is "ffooba". It basically reads the first character twice, as if the first time iterator++ executed, nothing happens.

Can anyone explain why this is happening?

+6
source share
4 answers

The thing iterator++ is not actually running the first time. The ++ operator returns the current value of the variable, and then increments it, so the first time through i++ will be 0 . && short circuit, so iterator++ not executed for the first time.

To fix this, you can use the comma operator, which unconditionally evaluates both, rather than the && short circuit.

+11
source

The result of i++ is the current value of i , which is zero at the first iteration. This means that iterator++ not executed on the first iteration due to a short call (the right side of && is executed only if the left side is "true").

To fix this, you can use the comma operator (as already suggested or) to use ++i , which will return the value of i after the increment (although the comma operator is more obvious that they should always be evaluated).

+5
source

You really need to learn how to use a debugger, for example, for example. gdb and compile with warnings and debugging information like gcc -Wall -g (assuming the system is Linux). Recent gcc with -Wall gives you a warning about a computed value, not used before the && operation.

The increment of part of your for loop is strange. This is i++ && iterator++ (but it should be i++, iterator++ ).

When i is 0 (in the first iteration), i++ gives 0 as a result, therefore it is false, therefore iterator++ not executed.

+3
source

I read K & R about logical operators, let me quote the original words of a book that may explain your question. "Expressions related to & / amp; or || are evaluated from left to right and the evaluation stops as soon as the truth or falsehood of the result is known." Have a good idea about this, the outputs will not be puzzles.

+2
source

Source: https://habr.com/ru/post/926572/


All Articles