casting a non-const variable to const.

Jun 19, 2013 at 4:49pm
Hi everyone
I'll be grateful, if someone can help me.

Is there any way to cast a non-const variable to const one?

I want to read variable n from file and then use it to declare array "int arr[n]", but because n is non-const, the compiler doesn't allow me to do that.
Jun 19, 2013 at 4:54pm
You don't want to cast it to a const, you want it to BE a const. This cannot be done.

Use STL container std::vector instead. See http://www.cplusplus.com/reference/vector/vector/
Jun 19, 2013 at 4:55pm
Array sizes have to be const and known at compile time, not run time.

Maybe you need a different container std::vector, std::list, std::map, std::set to name a few.

Here is a link to the tutorial on this site - check out he reference info & articles as well - all at the top left of this page.
http://www.cplusplus.com/doc/tutorial/typecasting/


HTH
Jun 19, 2013 at 4:59pm
Thanks AdrianH...
Jun 19, 2013 at 5:01pm
> I want to read variable n from file and then use it to declare array "int arr[n]",
> but because n is non-const, the compiler doesn't allow me to do that.

See: http://www.mochima.com/tutorials/vectors.html
Jun 19, 2013 at 5:06pm
to TheIdeasMan:
Thanks a lot...
but i think, when there is no need for dynamic memory allocation, working with array is much quicker than vector and so on...

however, thank you for your time :)
Jun 19, 2013 at 5:11pm
i think, when there is no need for dynamic memory allocation, working with array is much quicker than vector and so on

First of all, what makes you think so? And secondly, you actually have the need for dynamic memory allocation.
Topic archived. No new replies allowed.