C language > Beginner questions

+= operator question

(1/1)

Alessio:
Hi,

Why following code is compiled without error ?

--- Code: ---#include <stdio.h>

int main(void)
{
int c = 1;

c +=

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

return 0;
}

--- End code ---

Franzki:
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: ---#include <stdio.h>

int main(void)
{
int c = 1;

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

return 0;
}

--- End code ---

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: ---#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;
}
--- End code ---

Though the syntax is correct it *may* not do what you expected it to do...

Navigation

[0] Message Index

Go to full version