Absolutelyrun
Absolutelyrun

Reputation: 43

How is the array works while in a loop?

i'am learning C,and after learning the array,i want to try something,but here comes the confusion.

i try to print a-z but there are something more("{|") been printed.and i am confused with it.

int count;
char ph[26];
char x;
for(count = 0, x= 'a'; count < 26 , ph[count] = x; count++ , x++)
    printf("%c",ph[count]);

I expect the output to be a-z, but the actual output is a-|.

Thank you and I realize that what matters is the comma operator.

Upvotes: 0

Views: 91

Answers (2)

Bathsheba
Bathsheba

Reputation: 234875

The problem is that the stopping conditional expression

count < 26, ph[count] = x

has the value x, i.e. count probably runs past 25. This is how the expression separator operator , behaves.

If this means that you end up with an out of bounds read of ph (which you do on ASCII encoded platforms), the behaviour of your code is undefined.

The way you have written the loop is unnecessarily obfuscating, but if you want to stick to a similar way then writing

count < 26 && ph[count] = x

is the fix. Finally note that ASCII is not the only encoding supported by C, so even when you do get the program working on your platform, you have not written it in portable C.

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 311146

This for loop

for(count = 0, x= 'a'; count < 26 , ph[count] = x; count++ , x++)
    printf("%c",ph[count]);

is incorrect.

In the condition of the loop

count < 26 , ph[count] = x

there is used the comma operator. The value of the operator is the value of its second operand that is the value of the assignment ph[count] = x. The first operand count < 26 is just ignored.

As a result the loop has undefined behavior.

Rewrite the loop the following way

for(count = 0; count < 26; count++ )
    printf( "%c", ph[count] = 'a' + count );

Upvotes: 2

Related Questions