Precedence of post increment [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
Can anyone explain what will be the output of following code and why?
int main()
{
int i[] = {3, 5};
int* p = i;
int j = --*p++;
printf("%d\n%d\n", j,*p);
system("pause");
return 0;
}

I'm actually going to answer this question, even though it's true that "the OP simply needs to compile the code and run it", because it isn't obvious to a beginner that this is one of the cases where that gives the right answer. People get dinged all the time on this site for asking why superficially similar code (that does have undefined behavior) gives a surprising answer.
int j = --*p++;
means
int j = *p - 1;
*p = j;
p += 1;
That is, *p (the value that p points to) is decremented, the decremented value is written to j, and then p itself is incremented.
There is no undefined behavior here because the -- and ++ operators in the original form are acting on two different data objects. The expressions that have undefined behavior due to multiple use of the side-effect operators all involve modifying the same data object twice in the same expression ("without an intervening sequence point").
(If you're wondering why the -- applies to *p but the ++ applies only to p, the answer is "because that's what the grammar of the language says. Sorry, this is just one of those things you have to memorize.")

Related

Getting wrong output for a++ +b according to lexical analysis when the program is printed along with a+++b [closed]

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 months ago.
Improve this question
I wrote the following C program to find the output for a+++b
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a+++b);
}
And I'm getting the output as 7 which is correct according to lexical analysis.
Apart from that I wrote a separate program to find the output for a++ +b
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a++ + b);
}
For the above program again I'm getting output as 7 (which is again correct according to lexical analysis)
But when I wrote a program to print the outputs for both a+++b and a++ +b I'm getting different outputs
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a+++b);
printf("\n%d",a++ + b);
}
The output is 7 for a+++b (which is correct) and 8 for a++ +b (which is wrong).
Can anyone point out the error in the third program?
a++ is post-fix increment. It evaluates to a and increments the variable a by 1 before the enclosing printf() is called in this case(*).
So after the first printf() the value of a is 6.
So what do you now expect from the second printf?
Operators like post-fix ++ are expressions (have a value) and instructions (have an effect). They cause endless confusion bugs and undefined behaviour to novices and bite the most seasoned programmers on the ass from time to time.
(*) These operators are useful and have their place but exactly when these operators take effect is complex sometimes counter intuitive and I recommend you don't use them in complex expressions to begin with or even ever.
They're a bit of a throw back to when compilers didn't optimise code for you and the programmer had to help!
The issue here isn't the space in the second statement, it's the fact you have two of them. After the first statement (to be exact, after a++ is called), the value of a is incremented and is now 6. So a++ + b will clearly return 8. If you omit the first printf call and just call the second one, you'll get 7 as you expect.

Address is not incrementing? [closed]

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 6 years ago.
Improve this question
It is said that,in c,b++; is equal to b=b+1; if this is the fact test++ in my code why generate a compile time error.
test+1 is working well but test++ is not working.but why?
#include<stdio.h>
int main(void)
{
char test[80]="This is a test";
int a=13;
for(;a>=0;a--)
{
printf("%c",*(test++);
}
}
The ++ and -- operators are not defined for arrays.
v++; would be the same as v = v + 1;. Assumed v was typed an array this would imply assigning to an array, which is not defined.
char test[80] = "This is a test";
char *p = test;
for(int a = 0; a < 14; a++)
{
printf("%c", *(p++));
}
Well, for one thing, b++ is not the same as b=b+1.
But even if it were -- I think you'll find you get a similar error if you try test = test + 1.

Why this implementation of "strupr" don't work? [closed]

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 6 years ago.
Improve this question
Wrong implementation (compiled with gcc):
#include <stdio.h>
#include <ctype.h>
char* strupr( char *str )
{
while(*str) {
*str++ = toupper(*str);
}
return str;
}
int main(void) {
char string[] = { "Test String!" };
strupr( string );
puts( string );
return 0;
}
The function changes the string in an unexpected way, where the chars translated to upper case are only starting from the second char.
Note str is used twice in the assignment.
This implementation is invalid because it contains undefined behavior.
The explanation comes from section 6.5, paragraph 2 of the standard:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
The standard gives an example of an expression that is considered undefined behavior to clarify the second sentence:
a[i++] = i;
In this expression the value of i is read not only to determine the new value to be stored, but also to determine the storage location of another value.
This is precisely what is happening in your expression:
*str++ = toupper(*str);
The only difference is that your expression uses pointers, and calls toupper in between.
This requirement may seem arbitrary, but it has a reason. C standard allows the compiler to make side effects of ++ visible before or after the call of toupper to allow compiler writers maximum flexibility. Without a restriction on str's use in expression this could lead to different behavior on different platforms, so the standard writers decided to prohibit it outright.

Using a variable in its own declaration in recursion [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Using a local variable in its own initialization usually has no effect but doing it with recursion causes strange values. Why is there undefined behavior in the recursion but not outside of it?
#include <stdio.h>
void recurse(int count);
int main()
{
int j = j + 1; // a weird thing to do but its just 1
printf("%d\n", j);
j = j + 1;
printf("%d\n", j);
j = j + 1;
printf("%d\n", j);
recurse(1);
printf("\n");
}
void recurse(int count){
int i = i + 1; // the really weird part
printf("%d ", i);
if(count < 10)
recurse(count + 1);
return;
}
Output:
1
2
3
32737 1 32737 1 1 1 1 1 1 1
The large numbers are not always the same for each execution.
This is an example of undefined behavior.
Because the value can't be known before it is assigned, you can't predict what will happen. Running the same code on a different machine, or compiled with different settings, can yield different results.
Local variables (not initialized) have indeterminate value in C.
Reading them prior to assigning a value results in undefined behavior.
Nice quote from wikipedia article
In computing, an uninitialized variable is a variable that is declared
but is not set to a definite known value before it is used. It will
have some value, but not a predictable one. As such, it is a
programming error and a common source of bugs in software.
However, it is important to mention that in C, static and global variables not initialized will have the value = 0.

Are side effects of undefined behaviour in C defined? [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 8 years ago.
C code related to the question:
#include <stdio.h>
int main(int argc, char **argv)
{
int k = 0;
double b = k++ + ++k + k--;
printf("%d", k);
return 0;
}
The value stored in b is undefined, but what about k?
The place where I found this:
http://www.sanfoundry.com/online-c-test-precedence-order-evaluation/ Question #10
--EDIT--
What I found so far:
The value stored in b is not used anywhere, so if storing something into b would be the only UB, this program would not depend on UB.
But I also found this part in C99 6.5.2:
"Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression."
And listed under J.2. Undefined behavior:
" The behavior is undefined .... ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint is violated"
But the actual question is not answered yet.
-- EDIT #2 --
Not that I'm trying to write one, but a ''A strictly conforming program'' according to the standard :
"shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior"
So the orignal example was wrong, since it did depend on undefined behaviour, it would be undefined even if one would replace the line
double b = k++ + ++k + k--;
with the line
k++ + ++k + k--;
So right now I'm looking for a better presentation of what question is about.
As soon as we hit undefined behaviour, the compiler can do whatever it wants to - including formatting the disk if it has access rights. So nothing can be defined in this situation, including side effects.

Resources