|
| blast3r (3) | |||
Hey i just started reading c++ today, and i was wondering if someone could tell me why we would need this:
Why can't we just write that a = 4 in the start? sorry if this is a noobish question | |||
| jsmith (3794) | |||||
is completely valid and preferred to
| |||||
| felipe21 (21) | |||||||||
| Just to make it clearer. in C++ you declare and define variables.When you use:
you are just declaring a as an integer, and you have to define it later, but as jsmith said, it is perfectly valid to declare and define a variable in a single statement, like:
and in case you are wondering, you can also do this:
or if they are supposed to be initialized to the same value, even:
| |||||||||
Last edited on | |||||||||
| kempofighter (659) | |||
Or you can make it look like object construction which is how I like to do it. This makes it clearer that the variable a is being constructed and initialized with a value of 4.
| |||
| Duoas (3472) | |||||
int a = b = 7; is invalid -- b is not declared.The closest you can get to such a construct is the fugly int a = 7, b = a;. Personally, I think it is just better to declare each variable on its own line:
Hope this helps. | |||||
| felipe21 (21) | ||||
My mistake, actually what you can do to assign the same value to more than one variable is this:
| ||||
| vince510 (55) | |
you could do int a = int b = 7; | |
| Return 0 (653) | ||
That's not valid. | ||
| felipe21 (21) | |||||
That does not compile with in my machine.
| |||||
| Return 0 (653) | |
It's illegal syntax. The only time you can do something close to that is if all variables are declared prior. For example, in a default constructor call you could do this:a = b = c = d = 0; | |
Last edited on | |
| vince510 (55) | |
| oh my bad. thought it would work. | |
| wmheric (114) | |||
Remember = evaluates from right to left.a = b = 5;Since b = 5; returns the value of b, it can then be assigned to a a = (b = 5);.It compiles if the compiler knows what it means. It doesn't if the compiler have no idea of what it means. Referring to blast3r's question
The answer that immediately comes to my mind is that
| |||
Last edited on | |||
| twoscoops (15) | |
I know you can writeint a(4)but surely int is a primative type and as such not an object, and therefore not contructed? why can't we just write a = 4 at the start.... Well, you need to specify what type a is so int a = 4; is fine as is int a = 4, b = 7; But this has been said before. | |
| blast3r (3) | |
| Thanks for the answers. I think you guys misunderstood my question, but that may be because i asked it in a wrong way. but wmheric got me the answer thanks. | |
This topic is archived - New replies not allowed.
