Const but not at initialization

Suppose I have a variable x in a function; and I may set it to two possible values (depending on function computation paths). Once I set x, I do not change it.

Unfortunately, const requires x to be set at declaration.

Is there a way in an assignment x= val to say "from this point on, the value of x will not change"?

If you encapsulate the value inside a class/struct, this would be possible.
Here is an example:
http://coliru.stacked-crooked.com/a/679577c2b4d52143
closed account (SECMoG1T)
Hi , maybe the best option is just assign the computation value to a different temporary variable then intialize your x on declaration , am not sure if there is any other possible way, my idea here could still be viable.
Thanks andy and kevin. If I understand you right, this should be legal

1
2
3
4
5
6
7
8
9
... function(....)
{
  if (foo < 1){
    const double x = foo+foo;}
  else { 
    const double x = 2*foo;}
} 

closed account (SECMoG1T)
Yeah that's legal but not enough our problem is yet to be solved, you notice in that case you'll be creating two local variables in different scopes, am sure they can't be accessed outside those blocks, so it's like they get created and then destroyed almost instantly.
Last edited on
Oh yes, I forgot about scope, thanks for pointing that out!
Topic archived. No new replies allowed.