-2

Today I'm reading 《C-Programming》, when I'm copying the code from the book of a fahr-celsius converting function.

I saw codes like

int lower, upper;
lower = 0;
upper = 300;

And I'm wondering If I can do

int lower, upper;
lower, upper = 0, 300

in C, just like in python and golang.

So I did some experiment, I find if I did it, the file is compilable, but the result will be out of my expectation.

Here is my code and output:

# code

#include <stdio.h>

main()
{
    int lower, upper;
    lower, upper = 0, 300;

    printf("lower:%d\n", lower);
    printf("upper:%d\n", upper);
}


# output
lower:1
upper:0

I found no matter what number I tried assign to upper(like 1, -5, 20), the output will be the same.

What happened here?

Zen
  • 4,381
  • 5
  • 29
  • 56
  • `0, 300` is an expression that evaluates to `300`. There are no lists or tuples or whatever in C. – ikegami Aug 25 '20 at 04:29

1 Answers1

3

C doesn't support assigning tuples like Python does.

What this code does:

lower, upper = 0, 300

Is as follows:

  • Evaluate lower which is uninitialized, discard the resulting value
  • Assign 0 to upper
  • Evaluate the value 300

If you want to assign to two variables you need to do them separately, i.e.

lower = 0;  upper = 300;
dbush
  • 205,898
  • 23
  • 218
  • 273
  • 2
    Or `int lower = 0, upper = 300;` – Louis Go Aug 25 '20 at 03:45
  • Technically, evaluating `lower` invokes undefined behavior. – klutt Aug 25 '20 at 06:27
  • Why discard the resulting value will leads to lower = 1(the print result) – Zen Aug 25 '20 at 06:40
  • @Zen It doesn't. `lower` is uninitialized, so it's value is *indeterminate*. Attempting to read it causes [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior) so *any* value could be printed. – dbush Aug 25 '20 at 11:47