r/CodingForBeginners • • 22d ago

My first code on c++

I think i like this language

This code is a little messy and works only on windows, but it's easy to fix.

For anyone who wants to test it:

#include <iostream>
#include <cmath>
#include <windows.h>
// DIESER CODE IST VERDAMMT SCHRECKLICH
// variables
float power = 10.0;  // more power - bigger edges
float smooth = 4.0; // smoother edges
float len = 45.0;   // lines count

// main
int main() {
    while(1) {
        // l - current line
        for(int l=1; l<len; l++) {
            float l_sin = std::sin(l/smooth);
            int rep_times = l_sin * power + power;

            // line renderer | c - char
            for(int c=1; c<rep_times; c++) {
                Sleep(5);
                std::cout << "-";
            }
            Sleep(5);
            std::cout << "#" << std::endl;
        }
    }
}
140 Upvotes

12 comments sorted by

4

u/JohnBuddySlime 19d ago

Word of advice: try to avoid global variables when possible. You should always try to limit the scope of variables when possible, so declare and initiate them in your main. Also, favor bracket initialisation (int i{ 5 };) over c style initialisation (int i =5;)

1

u/Krastesoff 19d ago

Thank you!!

2

u/JohnBuddySlime 19d ago

Precision i forgot: this is the case for non-const variables. Const global variables are completely fine.

Also, from my experience (which is mostly academic and not professional, so if anybody can approve/correct my statement), non-const global variables should (mostly) only be used to save your program's state, for access synchronisation (in multithreaded programs for example), and for application wide variables (such as options given through command arguments or config files) (which technically also include the 2 previous cases, but I separated them for clearness' sake)

2

u/HotComplex4744 20d ago

windows.h не нужен, программа консольная. Бесконечный цикл while(1) - хреновая практика. А внутри break нету - это ваще пипец.

1

u/Krastesoff 20d ago

Спасиб!
Да, кривовато конкретно, есть такое))

1

u/kutac56 22d ago

What in this code uses windows.h?

3

u/RealRockyMoney 22d ago

I'm not a C++ guy but I think it is Sleep(5)

1

u/kutac56 22d ago

Just looked it up and you're right

2

u/Gold-Cat-9392 7d ago

Nowadays the trade of for longer names is not as strong as it was in old days. We have autocomplete in most ides including vim and nvim. So instead of // l- current line, I recommend you use for(int line...). It reduces the load when you are going through the code.
Your global variable len doesn't need to be in float, you are using it for integer indexing. Length as a integer value will suit more. Use float only if you are sure that the range for the variable includes decimals. Also use f for floats. `float power = 10.0f;` just a good practice

1

u/Kadabrium 21d ago

Now compare that to a brute force taylor sin