Yes, and Yes. For symbolic constants, there are two main ways. Either you could use a #define like in C, or you could simply declare the variable as either const or constepr.
As for foreach, it does exist. There are two versions of it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
// a container
std::vector<int> vec {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// version 1: Range-based for
for (int i : vec) {
std::cout << i << ' ';
}
std::cout << '\n';
// version 2: std::for_each
std::for_each(vec.begin(), vec.end(), [](int i){ std::cout << i << ' '; });
return 0;
}
How do you define symbolic constants like in C in C++?
The same way, by #define'ing them.
However as a C++ programmer you are encouraged to use constants instead.
1 2 3 4 5
// old-fashioned C/C++ code
#define PI 3.141593
// "the right way" C++ code
constdouble PI = 3.141593;
Code Apprentice wrote:
Also, are there such things as foreach in C++?
As of C++11 (the C++ standard of year 2011) there is the range-based for() loop, which can act as a foreach() loop.
Example code (will compile on Visual Studio 2013, GNU GCC 4.7+):
1 2 3 4 5 6 7 8 9
std::vector<int> vi {1, 3, 100};
// range-based for() loop to print all elements of vi
for (int i: vi)
std::cout << i << '\n';
// range-based for() loop to set all elements of vi to 13
for (int &i: vi)
i = 13;