NO

Author Topic: += operator question  (Read 2651 times)

Alessio

  • Guest
+= operator question
« on: June 19, 2008, 04:06:58 PM »
Hi,

Why following code is compiled without error ?
Code: [Select]
#include <stdio.h>

int main(void)
{
int c = 1;

c +=

printf("c value is %d\n", c);

return 0;
}

Franzki

  • Guest
Re: += operator question
« Reply #1 on: June 19, 2008, 08:05:32 PM »
the printf function is defined as:

int printf(const char * restrict format, ...);

The return value is the number of characters transmitted, or a negative value if an output or encoding error occurred.

Your code (with a semicolon missing) could also be written as:
Code: [Select]
#include <stdio.h>

int main(void)
{
int c = 1;

c += printf("c value is %d\n", c);

return 0;
}

So the number of characters written by printf is added to the value stored in 'c' and the result is stored again in 'c'.

This can be checked by adding another printf statement:
Code: [Select]
#include <stdio.h>

int main(void)
{
int c = 1;

c +=

printf("c value is %d\n", c);
printf("c value is %d\n", c);

return 0;
}

Though the syntax is correct it *may* not do what you expected it to do...
« Last Edit: June 19, 2008, 08:07:15 PM by Franzki »