Reputation: 971
I have just encountered some code and I'm not sure why it is done that way.
Note that this is quite old code, so for (auto i : x)
is not an option.
The code is:
INT_PTR i,c;
for(i=0,c=m_array.GetSize();i<c;i++)
{
// Do stuff, i & c are not changed inside the loop
}
Where as I would have done (well I would have used single letter variables, but thats another argument:
const INT_PTR c = m_array.GetSize();
for (INT_PTR i = 0; i < c; i++)
{
// do stuff
}
Is there some performance advantage of the first approach that I don't know about?
Upvotes: 0
Views: 102
Reputation: 14589
Once upon a time in some compilers long forgotten the first way was the only way in C.
In older dialects, including original ones , functions would be defined like this:
int foo(a, p)
int a;
char *p;
{
}
and declared like this:
int foo(int , char ) ;
int foo2(); // unknown arguments
int foo3(void); // no arguments
Variables had to be declared before any other code happen and their life length and visibility was prolonged until function would return to its caller. The aforementioned syntax at first was the only one, later declaration was included into for()
header but variables would be still visible outside. Great changes later came with ANSI and ISO standards.
In modern C and C++ the original style of for loop leads to visible variables that may stay uninitialized if for()
didn't contain initialization and no iteration had happened. An advantage of it is that you can "initialize" variables of incompatible types even before C++17 (the quotes are there because technically it's assignment and C++ throws in different rules for those):
float arr[] = { 3,4,5,6 };
int i, e;
float v;
for( i = 0, e = sizeof(arr)/sizeof(arr[0]), v = arr[i]; i < e; v = arr[++i] )
{
}
At work as soon as I see some other programmer use C style of function design in C++ project, I begin to scrutinize that code. Sometimes they accidently introduce UB or incorrect behaviour because they apparently follow K&R C rules. Or had plagiarized it from somewhere.
Upvotes: 1
Reputation: 137
I don't think that there is a difference between the code examples. However, a "intelligent" compiler will optimize this anyway.
Upvotes: 3