Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to array[1]

I have a large block of code that is designed to take an array and work through it. In the current project there will be only one element so instead of changing the variable to a char i declared it as char array[1]. This way i do not need to modify my code and risk adding any bugs and can easily increase it if the requirements grow.

It appears to compile ok but i have become curious about what is happening under the hood, am i wasting memory ? is this adding extra processing time, will the compiler optimise it all away so it would be no different if i typed it out ?

can anyone explain any possible drawbacks to using arrays is this way.

I use c and c++, would it be any different between them ?

like image 626
Skeith Avatar asked Nov 30 '22 20:11

Skeith


1 Answers

Sounds like a good strategy, and there are no drawbacks. You are defintely not wasting memory in either C or C++. The memory taken by an array of size one is the same as the memory taken by a variable of the same type.

It's possible the compiler will generate microscopically less efficient code, but that is really not worth worrying about.

like image 168
john Avatar answered Dec 03 '22 08:12

john