1

I not very familiar with C++, have some issues with the multiple assignments

int a = 0, b = 0; 

works

int i; double d; char c; c = i = d = 42; 

also works but why this does not works.

int a = 4, float b = 4.5, bool ab = TRUE; 
9
  • 1
    It doesn't work because those are the rules of C++. Differing types cannot be declared in a single line like that. Commented May 15, 2021 at 22:21
  • 1
    Because the language was designed that way: you can only declare multiple variables with the same base type. Also note that your bool should be true, not TRUE. Commented May 15, 2021 at 22:21
  • But int a = 4; float b = 4.5; bool ab = true; // in one line works. Commented May 15, 2021 at 22:23
  • 1
    @CEPB "I think c = i = d = 42; is UB" no, this is well defined. "What if you do c = i = d = 55555" yes, that's UB if it causes a signed overflow. For unsigned wrap around it's still well defined. char can be unsigned or signed. It implementation defined. Commented May 15, 2021 at 22:27
  • 1
    Thanks, so it is the language rule, I see. @PaulMcKenzie Commented May 15, 2021 at 22:28

1 Answer 1

4

This is to do with the allowed syntax. The format is, in very high-level terms, roughly:

type varName [ = expr ][, varName [ = expr ] ]?; 

Where there is no allowance at all for another type to be introduced mid-stream.

In practice declaring multiple variables per line can lead to a lot of ambiguity and confusion.

Quick quiz: What is the initial value of a? What type is b?

int* a, b = 0; 

If you guessed a was a NULL pointer and b was int* you'd be wrong. This is why it's often preferable to spell it out long-form so there's absolute clarity:

int* a; int b = 0; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.