34

I want to assign 0 to all declared values in a single statement.

char r, g, b = 0;

The above only assigns 0 to b but not to the other variables

2
  • I guess the stament is, the above only assigns 0 to b rather than r ? Commented Sep 27, 2011 at 8:06
  • Just tested this. You're right. Accepted your edit. Commented Sep 27, 2011 at 8:13

2 Answers 2

55

You can do it two ways:

char r = 0, g = 0, b = 0;

or

char r, g, b;
r = g = b = 0;
Sign up to request clarification or add additional context in comments.

5 Comments

So this is as terse as it gets?
@Plenilune Yes, or you should make them static like Sandip suggested.
NO! Don't make them static. While that inits them to zero, you still have to reinit them if you want them reset, and using static will introduce all sorts of other problems. Your second solution is the right one.
@Plenilune: C isn't terse enough for you? 8-)}
Does assignment happen right to left or left to right?
21

Tersest form is:

int r,g,b=g=r=0;

2 Comments

Never saw that before! Finally I know how to get it done in a one liner! (order of g and r isn't important, right? They just have to be after b, right?)
haha nice one :D @winklerrr the rest after b yeah, order doesn't matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.