Pelles C forum

C language => Beginner questions => Topic started by: Alessio on June 19, 2008, 04:06:58 PM

Title: += operator question
Post by: Alessio 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;
}
Title: Re: += operator question
Post by: Franzki 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...