#include <iostream>
usingnamespace std;
#define PI 3.1416
int main ()
{
int x;
cout << "Escribe un numero:";
cin >> x;
cout << "\n";
if (x >0)
cout << x <<" es positivo";
elseif (x <0)
cout << x << " es negativo";
else cout << x << " es 0";
cout << '\n';
int a;
a=0;
while (a!=x)
{cout << a << ',';
a++;}
}
write a negative in the input and you will understand my question
#include <iostream>
usingnamespace std;
#define PI 3.1416
int main ()
{
int x;
cout << "Escribe un numero:";
cin >> x;
cout << "\n";
int a = 0;
if (x >0)
{
cout << x <<" es positivo" << '\n';
while (a!=x)
{
cout << a << ',';
--a; // here
}
}
elseif (x <0)
{
cout << x << " es negativo";
while (a!=x)
{
cout << a << ',';
++a; // here
}
}
else cout << x << " es o";
}
(It will actually end eventually. Once the numbers get too big and it overflows they will loop around and become negative. I would not recommend waiting for this to happen.)
> It will actually end eventually.
> Once the numbers get too big and it overflows they will loop around and become negative.
When an arithmetic operation on a signed integer results in an overflow, the behaviour is undefined.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <limits>
int main()
{
int a = std::numeric_limits<int>::max() ;
constint b = a ;
std::cout << "a == " << a << " b == " << b << '\n' ;
std::cout << "just before engendering undefined behaviour\n" << std::flush ;
++a ; // *** engenders undefined behaviour ***
std::cout << "after ++a, " ;
if( a == b ) std::cout << "a is equal to b\n" ;
elseif( a > b ) std::cout << "a is greater than b\n" ;
else std::cout << "a is less than b\n" ;
}
clang++ without -ftrapv
a == 2147483647 b == 2147483647
just before engendering undefined behaviour
after ++a, a is greater than b
g++ without -ftrapv
a == 2147483647 b == 2147483647
just before engendering undefined behaviour
after ++a, a is less than b
clang++ with -ftrapv
a == 2147483647 b == 2147483647
just before engendering undefined behaviour
bash: line 10: 13572 Illegal instruction (core dumped) ./a.out
undefined behaviour generated a trap