Un3qual
Un3qual

Reputation: 1342

Declaring multiple variables on one line out of order

I recently saw this in some Java code:

int pos = -1, ch;

Is that the same as

int pos, ch = -1;

?

Upvotes: 0

Views: 946

Answers (3)

RohitS
RohitS

Reputation: 1046

i would say yes...the only difference being what you are initializing (in first statement you assigned value to first variable and other left untouched so only first variable is initialize to value and other just remain a reference variable of type int) the same is true for Second statement...

if you say :

int x=10,y;

here x is initialized to value 10 and y to default (ie 0 but compiler will throw compilation error "variable y might not have been initialized!" )

but if you say

int x,y=10;

then x is set to default (ie 0 again compilation will throw compilation error variable x not initialized !) and y is set to value 10

what does not matter here is the order of occurrence for x and y.. hope that clarifies! :D

Upvotes: 1

Wojtek
Wojtek

Reputation: 1308

In both lines two variables are being created. In the first one only pos is initialized with -1 and in the second one only ch is initialized with -1. Before you use the uninitialized ones, some values should be assigned to them.

Upvotes: 0

Leon
Leon

Reputation: 3036

No, the first code snippet only initializes pos with -1 and leaves ch uninitialized. The second one does it the other way round leaving pos uninitialized and ch with the value -1. But in either case, both ch and pos will be created and you will be able to set or update their values.

Upvotes: 2

Related Questions