Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program interesting behaviour

Tags:

c

for-loop

I have stumbled upon a piece of code that generates some interesting results while debugging someone else's program.

I have 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 that this is not the right way to print a string. This is for demonstration purpose only.

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

Can anyone explain why this happens?

like image 1000
Ionut Hulub Avatar asked Sep 29 '12 06:09

Ionut Hulub


3 Answers

The thing is iterator++ actually isn't executed the first time. The ++ operator returns the current value of a variable and then increments it, so the first time through, i++ will be equal to 0. && short-circuits, so iterator++ is not executed the first time.

To fix this, you could use the comma operator which unconditionally evaluates both, rather than the short-circuiting &&.

like image 102
icktoofay Avatar answered Oct 16 '22 11:10

icktoofay


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

To fix you could use the comma operator (as already suggested or) use ++i which will return the value of i after the incremement (though comma operator is more obvious that both must always be evaluated).

like image 24
hmjd Avatar answered Oct 16 '22 12:10

hmjd


You really should learn to use a debugger like e.g. gdb and to compile with warnings and debugging info like gcc -Wall -g (assuming a Linux system). A recent gcc with -Wall gives you a warning about value computed is not used before the && operation.

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

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

like image 28
Basile Starynkevitch Avatar answered Oct 16 '22 10:10

Basile Starynkevitch