Assignment expression return value
What you'll learn: How to use the fact that an assignment itself produces a value that can be reused immediately.
The Secret Result
In most programming languages, you think of an assignment (like x = 5;) as a command that just "happens." You tell the computer to put 5 into x, and it’s done. However, in C, an assignment is actually an expression that returns a value.
Think of it like a professional delivery driver. Their primary job is to drop a package off at a house (assigning the value). But once the delivery is complete, the driver returns to the hub with a signed receipt confirming exactly what was delivered. In C, the "receipt" is the value itself. When you write x = 5, the entire expression evaluates to 5.
Chaining Assignments
Because an assignment returns the value that was just assigned, you can link them together like a bucket brigade. This is commonly used to set multiple variables to the same starting point.
int a, b, c;
// The value 10 flows from right to left
a = b = c = 10;
// Why this works:
// 1. (c = 10) happens first and returns 10.
// 2. (b = 10) happens next and returns 10.
// 3. (a = 10) happens last.
Instead of writing three separate lines, the "return value" of c = 10 is handed off to b, and so on.
Real-World Use: The "While" Shortcut
You will often see this trick inside the conditions of loops. Imagine you are reading characters from a keyboard. You need to do two things: save the character to a variable and check if that character is the "Enter" key.
Without using the return value, you’d have to get the character, then check it, then get it again inside the loop. By using the assignment’s return value, you can do it all at once:
char letter;
// Assign the input to 'letter', THEN immediately check if it's 'q'
while ((letter = getchar()) != 'q') {
printf("You pressed: %c\n", letter);
}
In this example, letter = getchar() happens first. The result of that assignment is then immediately handed over to the != 'q' comparison. It makes your code more compact and ensures you aren't repeating yourself.
Key takeaway
An assignment doesn't just store a value; it "becomes" that value, allowing you to chain operations or check values the moment they are stored.