Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Here is the simple code of for loop. Theoretically after for loop, the value of i should increase to 1 but the value is not increasing; i retains the value 0 after the loop also. Can you provide me the reason behind this?
Integer j = 0;
Integer i = 0;
for(; i < m_ParticleNum; ++i)
{
if(m_aOutputParticleID[i] < 0 )
{
m_aOutputParticleID[i] = i;
m_aOutputParticlePosition[i] = bucket[j].Position;
m_aOutputParticleVelocity[i] = bucket[j].Velocity;
m_aOutputParticlePressure[i] = bucket[j].Pressure;
m_aOutputParticleDensity[i] = bucket[j].Density;
m_aOutputParticleTemperature[i] = bucket[j].Temperature;
m_aOutputParticleKineticViscosity[i] = bucket[j].KineticViscosity;
m_aOutputParticleSolidPhaseRate[i] = bucket[j].SolidPhaseRate;
m_aOutputParticleType[i] = bucket[j].Type;
j++;
}
}
If the value of m_ParticleNum is 0, the loop does not execute and so, the value of i stays 0.
Is the value i used in any calculation or output after the loop?
If you are just inspecting i using the debugger, it may be optimised so it doesn't retain a value. There is no guarantee that the compiler has to retain values in unused variables.
Also, if there is any range checking going on which causes the loop to be exited with an exception, the increment of i at the bottom of the loop will be bypassed.
Finally, as i is a user-supplied class Integer, it is possible that some nasty person has defined its operators so the ++ operator is broken/disabled by design and is not incrementing the value.
We really need to see how you are evaluating i after the loop and the declaration of the type Integer to be able to provide a better diagnosis.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
Giving this code:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int k, x;
while(k > x-3) {
k--;
// cout << "x = " << x << "\n";
}
x++, k--;
int aux = abs(k-x);
cout << aux;
}
When we run it, it always pops up a constant x (x = 50) and the absolute value between the integer k and the x is always 5. Can you please explain me why and how does this works?
With the constraint of "k is greater than x", this piece of code here
while(k > x-3) {
k--;
// cout << "x = " << x << "\n";
}
Will decrease k to be 3 less than x.
The next line, x++, k++; increases them both by 1, but it doesn't change the result. k is still 3 smaller than x.
k-x is -3 and abs(k-x) is 3, hence why the program always prints 3. Assuming, of course, that both k and x are initialized and that k is bigger than x. The program as it is posted with k and x uninitialized exhibits undefined behavior, so there's no guarantee on what is going to happen. Also, as Aconcagua points out, if x is smaller than INT_MIN + 3, that also leads to undefined behavior.
I really think you should try two arbitrary numbers.
For example , imagine we are using k= 10 & x=8.
Your loop will look like:
While(10>5) 10-1=9 ... and so on, until K is not greater than (X-3).
You will get k=5, and x is the same value,8.
After the while loop you decrement k, and increment x, so k=4 and x=9.
Abs(k-x) = 5.
If you want the more theoretical explanation, the loop will grant that the difference between your two variables is 3, the X will be greater than K.
As after the loop you decrement K and increment X , the diference between them will ALWAYS be 5.
Matthieu and πάντα ῥεῖ are correct: Ths is classic undefined behavior. (One rationale for making it undefined and not simply unspecified or implementation defined is that some architectures have flags for uninitialized registers and would trap.) A compiler is actually free to compile it to an empty program: Reading an uninitialized variable can result in anything — and nothing is a subset of anything. All subsequent code after the undefined behavior is "tainted" by the preceding error and can be omitted. Note that different architectures and different compilers, possibly even different C standard libs (with the same compiler!) may give different results; even a different compiler flag (concerning optimization or function call conventions) may change this undefined behavior.
(The rest of this answer applies to the version of the question where the line after the loop read x++, k++; (instead of k-- as it is now).)
But you have encountered a consistent behavior, and the question is why it is consistent. The first assumption is that the compiler does not simply generate code to output "5", (which it could, legitimately) but actually "naively" generates machine code that corresponds to the C statements. We'll reason along the statements.
Then the behavior indicates that the memory locations where x and k reside are containing values which make k > x -3 false right away. (Otherwise, k would be decremented until the difference is 3, not 5).
If the condition is false, the variable difference will not change; from that we can conclude that it was 5 from the start with x-k == 5. If you omit the abs(), the output should be -5.
The reason the variables have these consistent intial values may be connected to things the operating system or C runtime environment do at program startup, like initializing the standard streams. Try using printf instead of cout and see if the result changes.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This is my code. It seems that f[i] returns 1 at any value of i.
int f(int x) { return 203; }
int main(){
cout<<f[0]<<' '<<f[21]<<' 'f[-1];//= 1 1 1
return 0;
}
Using the warning thrown by the compiler I understand that this is a pointer but it doesn't seem to behave like one.
f[-2](1) // = 203, good
f[32](1) // Process returned -1073741571 (0xC00000FD) execution time : 6.731 s
EDIT: I use the g++ compiler with the c++ 14 flag.
It is a GCC extension:
6.23 Arithmetic on void- and Function-Pointers
In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.
A consequence of this is that sizeof is also allowed on void and on function types, and returns 1.
Resulting pointers to non-existent functions, if called, would most likely crash or produce weird results.
It seems that f[i] returns 1 at any value of i.
That's a well-known behaviour of cout. It prints all non-zero function pointers as 1, because there is no proper overload of operator<< for them, and operator<<(bool) gets chosen as a most suitable overload.
(f[i] is a function rather than a function pointer, but it decays to a pointer in this case.)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Debug why the below mentioned code goes into an infinite loop
int a[10];
int i;
for(i=0;i<=10;i++) {
a[i]=0;
}
i am not able to find any valid explanation for it.
Although one possibility is a[9] pointing back to i ... but it doesn't seem convincing
Classic side effect of "Buffer overflow". In this case what is happening is that the value of i is getting overwritten. Check the range of variable a it's an array of 10 bytes 0 through 9. However you loop for 11 bytes 0 through 10.
Change the loop as
int a[10];
int i;
for(i=0;i<10;i++) {
a[i]=0;
}
and it won't go in infinite loop. Again this is a problem of "buffer overflow" and can have undefined behavior. In your case that undefined behavior is infinite loop.
For the value of i equals to 10,
a[i]=0;
is off by one access. It invokes undefined behavior. Anything can happen.
This code has undefined behavior. But if it is going into infinite loop the most suitable explanation would be that a[10] = 0 is overwriting i with 0, since i is defined immediately after a, therefore, in memory is most probably placed as a contiguous element after array elements.
You could try this so that you don't get undefined behavior:
int i, a[10];
for(i = 0; i <= 9; i++)
a[i]=0;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I recently started learning C++ and I'm a bit confused with pointers. Could you please explain me WHY in the following example variable "a" equals 1 and z = 0?????? I'm really confused!!!!!!
#include<iostream>
using namespace std;
void main()
{
int a;
int Z[3] ={1, 2, 3};
int *z;
z=Z;
a = (*z)--;
cout<<a<<" "<<*z<<"\n";
system ("pause");
}
logically ,I believe, first of all *z points to the 0-th element of the array - that is 1
then -- operator decreases 0-th element's value by 1 and now z[0] should be 0
but WHY it still returns 1 for "a" variable????
The order of your operations is this:
a = *z //*z = 1 here
*z = *z - 1 //*z = 0 here
Decrement operator happens after the assignment.
It is because the decrement operator is after the expression.
a = (*z)--;
Here first *z is evaluated and a is assigned the value (1). After that *z is decremented to zero.
If it had been
a = --(*z);
Then *z would have evaluated and decremented 1st. After that the value would have been assigned to a. Hence in this case both would be zero.
Post-decrement, thing--, yields the value before decrementing; so a is assigned the previous value of *z, which is 1.
Pre-decrement, --thing, yields the value after decrementing, so changing to a = --(*z); would set a to zero.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this confusion about conditional statements which may be applicable to almost all programming languages.
Like for instance this C++ code:
int main()
{
char *ptr, arr[]={'C','O','M','P','I','L','E','R','\0'};
ptr = arr;
*ptr = 'Z';
while(*ptr++)
cout << *(ptr-1);
return 0;
}
As what I have learned, a conditional statement executes only when the expression is true. So in this case, this part:
while(*ptr++)
The compiler considers all the characters being true except for the NULL. So meaning to say only NULL is false in this case? And it's alright to do this with characters?:
if('x'){do something}
while(*ptr++)
will keep going till the time ptr does not point to the end of this string which is \0 (Null Terminator) , This same statement also increments ptr to point to next value on each run, so essentially its saying while this condition is true, keep going. And the condition is while ptr still points to an element of arr;
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
Reference
Edit:
But why is it accepting arguments like: while('x')? A letter 'x' is true?
No it doesn't mean the letter itself is true, it means that its not NULL, which is 0. Consider it like this.
while('x')
is the equivalent of saying
while('x'!=0) // so that is perfectly acceptable and understandable
Edit 2:
Here is a simpler example for you to be able to better understand
#include <iostream>
int main()
{
int x=0;
if(x)
{
cout<<"If this is shown, x was not 0.";
}
if(x==0)
{
cout<<"so does it mean x is true? no: It means your condition 'x==0' is true";
}
}
In C, any number apart from 0 is considered true. (0 is false)
If you iterate over an array with *prt++, it checks if the currect index is not zero and increases the pointer.
if ('x') is perfectly valid, but it will always be considered true.
(Remember that char internally is but an 8 bit number and 0 is used to terminate strings. In the example you provided, it is used to iterate over the "string")
And yes, NULL is also considered false (because the address the pointer points to is 0), however, in the example you provided, the pointer gets dereferenced first, so it checks at the place it points to.
It is a relic of C that anything non-zero will evaluate to a boolean true when it is tested, such as your if ('x') above. x has an integer value as it is a character of non-zero value, therefore the expression would evaluate true.
In the case of the pointer iterating over the character array, C 'strings' are always ended in '\0', null, which when the pointer gets there will be the time where the while will fail as null == 0. Not to be confused with '0' as '0' is a character and has an integer value.