Madona wambua
Madona wambua

Reputation: 1428

Incrementing variable in printf()

I was watching a tutorial online and did not fathom why we needed to use this:

printf("The value is 7: [ %d]\n",k++);

So, this is what I have:

int k = 6;
k++;

printf("The value is 7: [ %d]\n",k);

Output:

The value is 7: [ 7]

Now this is what he did:

 int k = 6;
 k++;

 printf("The value is 7: [ %d]\n",k++);

Output:

The value is 7: [ 7]

This one too will print out 7:

int k = 6;

printf("The value is 7: [ %d]\n",k++);
printf("The value [%d]\n", k);

Output:

The value is 7: [ 6]
The value [7]

My confusion was what is the importance of incrementing in printf() ?

Upvotes: 2

Views: 6365

Answers (4)

mtszkw
mtszkw

Reputation: 2783

my confusion was what is the importance of incrementing in printf?

There is no importance.

These examples are always only to show people like you how do pre- (++k) and post-incrementing (k++) operations work. There is no strict rule about incrementing variables inside of printf().

You don't need to do this, but it is very valuable operation, worth knowing.

++k is called pre-incrementation: value of k will be incremented first, then used.
k++ is called post-incrementation: value of k will be used first, and then incremented by 1.

Upvotes: 5

Habib Kazemi
Habib Kazemi

Reputation: 2190

Rules:

1.when you use k++ it will increment the k.

2.when you use for example int b=k++; b will be 6 and k will be 7

  1. when you use int b=++k; the b and k will be 7.

so here in

 int k = 6;
 k++;
 printf("The value is 7: [ %d]\n",k);
 return 0;
 }

so as a first rule k++ ---> k will be 7 and printf will print 7.

the secod code:

int k = 6;
k++;
printf("The value is 7: [ %d]\n",k++);
return 0;
}

first rule:k will be 7.

it's like the second rule: the k's value pass to the printf then k will incrementso if you put printf("The value is 7: [ %d]\n",k); after that printf it will print 8.

in the third code:

 int k = 6;
 printf("The value is 7: [ %d]\n",k++);
 printf("The value [%d]\n", k);

here first printf will print 6 because k will pass to it before increment and it's 6 then k will increment and the second printf will print 7.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

The expression k++ evaluates to the value of k. As a side effect, the value of k is incremented.

When you use:

int k = 6;
k++;
printf("The value is 7: [ %d]\n",k);

printf will print 7. The value of k after printf is still 7.

When you use:

int k = 6;
printf("The value is 7: [ %d]\n",k++);

printf will print 6. The value of k after printf is 7.

Upvotes: 0

Bill Lynch
Bill Lynch

Reputation: 81916

The expression k++ returns the value of k before the increment, and as a side-effect will increment itself.

So this code:

int k = 6;
k++;
printf("The value is 7: [ %d]\n",k++);

Will print 7, but k will have a value of 8 after the printf line.

Upvotes: 0

Related Questions