Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#define size_int unsigned long long

void Increment(size_int value) {
  size_int len = 0;
  for (size_int i = 0; i < 100000; i++) {
    len = len + 1;
  }
}

Why does this crash my program? I have tried incrementing a billion different ways, i don't understand this is so wierd.

What I have tried:

I have tried other techniques, such as:
len++;
len += 1;
++len;
len = len += 1;
len = len++; //this was a wild card
Posted
Updated 3-Dec-21 8:13am

When I try that at onlinegdb, it compiles and runs fine:
#include <iostream>

using namespace std;

#define size_int unsigned long long

void Increment(size_int value) {
  size_int len = 0;
  for (size_int i = 0; i < 100000; i++) {
    len = len + 1;
  }
}

int main()
{
    cout<<"Hello World\n";
    size_int x = 666;
    Increment(x);
    return 0;
}
If I modify it to do something useful, it still works:
#include <iostream>

using namespace std;

#define size_int unsigned long long

size_int Increment(size_int value) 
{
    for (size_int i = 0; i < 100000; i++) 
    {
        value++;
    }
return value;
}

int main()
{
    cout<<"Hello World\n";
    size_int x = 666;
    cout<<Increment(x);
    return 0;
}
I get
Hello World
100666

So I suspect that's not the code you are running.
 
Share this answer
 
This code works for online GDB: GDB online Debugger | Compiler - Code, Compile, Run, Debug online C, C++[^]

I can't see why or how this code could crash. At worst, if run on a 16 bit OS, it woud overflow - but it wouldn't crash, since you're not actually using any of these values.

What compiler are you using? What OS?

On a sidenote, all of the variants you listed should yield the same result (and the recommended method would be ++len, not len++ or any of the others)

P.S.: if this is supposed to be C++ code, then you should change the first line to:
C++
using size_int = unsigned long long;
In C++ code you should avoid #define macros as much as possible!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900