0

How do I break out of this loop and set initialize to 1 so it stops my for loops? I want to use this function once and only once.

void initialize(double weightType) {
            int initialized = 0;
            std::cout << initialized << std::endl;
            if (initialized < 1) {
                std::cout << initialized << std::endl;
                for (int wl = 0; wl < layersWeights.size(); wl++) {
                    for (int r = 0; r < layersWeights[wl].size(); r++) {
                        for (int c = 0; c < layersWeights[wl][r].size(); c++) {
                            layersWeights[wl][r][c] = setRandom();
                            std::cout << layersWeights[wl][r][c] << std::endl;
                        }
                    }
                } 
                initialized = 1;
            }
        }
BenGlynd
  • 11
  • 3
  • 4
    I think that you do not want to break out of the loop, but only execute it during the first call. For that, make it `static int initialized = 0;`. If you really want to break out of the loop, a return statement at the appropriate point will do it. Also, making initialized a bool would be a better choice. – Avi Berger Sep 16 '22 at 04:15
  • You're already out of the last for loop where you've written `initialized = 1` so **there is no need to add `break` or anything**. – Jason Sep 16 '22 at 04:18
  • If you come from an OO language like C#: you can put `static int` inside the method, which is called local static. Such a feature does not exist in C#. – Thomas Weller Sep 16 '22 at 04:27
  • Looks like you use global variables (e.g. `layersWeights`). Since you tagged your question with C++, maybe you could wrap this code in a class, where `layersWeights` will be a member. If you do it like that you can add another member like `bool bInitialized` that will hold the initialization state. – wohlstad Sep 16 '22 at 04:38
  • This is explained in any beginner [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Sep 16 '22 at 04:43

0 Answers0