#include <QCoreApplication>
int ages[4] = {23,7,75,1000};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInfo() << ages;
for (int i = 0; i < 5; i ){
qInfo() << i;
}
a.exec();
return 0;
}
returns:
0x7ff7d01f3010 0 1 2 3 4
To the terminal
But
#include <QCoreApplication>
int ages[4] = {23,7,75,1000};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInfo() << ages;
for (int i = 0; i < 5; i ){
qInfo() << i;
qInfo() << ages[i];
}
a.exec();
return 0;
}
returns:
4713 0 4714 0 4715 0 4716 0 4717 0 4718
etc. to the terminal.
As a beginner this behavior is not intuitive and I do not understand what the difference is.
The first code was my attempt to see if my for loop was written incorrectly, but it acts as expected.
CodePudding user response:
You have undefined behaviour in your code because you are indexing the array out of its size. Your array has four elements, but you seem to try to access 5 elements in its. So, the last iteration is undefined behaviour.
You could write this instead:
#include <QCoreApplication>
int ages[4] = {23,7,75,1000};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInfo() << ages;
for (int age : ages)
qInfo() << age;
a.exec();
return 0;
}
Depending on your compiler, you could use the sanitizer options to catch these, for example:
-fsanitize=undefined
I personally use these in my projects:
if (CMAKE_CXX_COMPILER_ID MATCHES "(Clang|GNU)")
add_compile_options(-Wall -Wpedantic -Wextra -Werror)
add_compile_options(-fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer)
add_link_options(-fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer)
elseif (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
set_property(DIRECTORY APPEND PROPERTY COMPILE_OPTIONS "/w")
endif()
add_compile_definitions(QT_DISABLE_DEPRECATED_BEFORE=0xFFFFFF)
I would also like to point out that you should use size_t
instead of int
for the loop counter as a good practice.
It is also worth pointing out that you should avoid using raw arrays in a C , and especially Qt program. There are better choices, like:
std::array
std::vector
QList
etc.
Furthermore, you could even merge these two lines:
a.exec();
return 0;
Into the following (this is how it is typically written):
return a.exec();