Hello everyone,
quick question, wanting to know if both these lines of code mean the same thing.
int left, right = 0;
&
int left = 0;
int right = 0;
thanks for clearing this up for me.
Hello everyone,
quick question, wanting to know if both these lines of code mean the same thing.
int left, right = 0;
&
int left = 0;
int right = 0;
thanks for clearing this up for me.
Yes. The comma operator can be used to separate complex expressions. For example, you could also do silly stuff like:
for (int i, j = 9; j < 10; j++)
That said, most use the single line definitions rather than stacking them.
"int left, right=0;" defines two integer variables (left and right), but only initializes "right" to zero.
It has nothing to do with the comma operator. (isn't C syntax wonderful?)
To initalize them both you could do
int left=0, right=0;
or
int left, right;
left=right=0;
the following is also a legal set of C statements (an example of the comma operator), but is probably not a useful for anything.
(The comma operator should be avoided, almost always.)
int left, right;
left = right, 0;
It has nothing to do with the comma operator.
Really? Try the statement leaving the comma operator out of the statement. The comma operator does exactly what I said it does: It can be used to separate complex expressions.
westfw:
"int left, right=0;" defines two integer variables (left and right), but only initializes "right" to zero.
If you define a variable without giving it a value, is it not automatically initialised to zero?
I was under the impression that "int x;" and "int x = 0;" were exactly the same, although the former should be avoided for the sake of clarity.
If you define a variable without giving it a value, is it not automatically initialised to zero?
C++ is not required to initialize local variables. Some compilers do; other don't. Best practice: Assume local variables are initialized with garbage.
use this instead, its much faster and means the same thing
int right,left;
"int a,b;" is not an instance of the comma operator...
Comma operator - Wikipedia :
"The use of the comma token as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator."
Also Comma in C - GeeksforGeeks
comma operator clarification
global variables are initialized to zero. Local variables are not initialized unless you provide the initialization.