Why is *a++; not incrementing the value a points to? [duplicate] - c++

This question already has answers here:
Does *p++ increment after dereferencing? [duplicate]
(5 answers)
Closed 6 months ago.
Hellow
I am a beginner in coding who is learning pointer. this is a simple code of passing pointers
to functions but I am getting wrong input.
#include<iostream>
using namespace std;
void increment(int *a){
*a++;
}
int main(){
int a=2;
//int *p=&a;
increment(&a);
cout<<a;
return 0;
}
output is showing 2;

What happened here? The C++ grammar effectively defines something we commonly refer to as "operator precedence" (since it's defined by the grammar, you won't find chapter in the C++ standard where the precedence would be listed in a convenient way, but there are websites that worked it out).
In *a++;, the pointer will be increased (a++) and thus pointing to an invalid position. After that, the invalid pointer will be dereferenced (* operator), causing undefined behavior (UB). If you're learning, you want to get familiar with undefined behavior, because anything can happen.
To fix it, use parentheses to specify precedence explicity: (*a)++;.
Maybe you want to learn about references instead? Don't use raw pointers and pointer arithmetic. Compare your code to this code:
#include<iostream>
using namespace std;
void increment(int& a){
a++;
}
int main(){
int a = 2;
increment(a);
cout << a;
return 0;
}
Also: Why is "using namespace std;" considered bad practice?

Related

Cout works well on wrong-written function [duplicate]

This question already has answers here:
Why is the phrase: "undefined behavior means the compiler can do anything it wants" true?
(2 answers)
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
(11 answers)
Closed 5 months ago.
I try to help people learn to code in C++ and I received an answer for an easy task to write a code that gets three numbers as input and outputs a sum of them. I received a wrong-written code with no return statement which... suprisingly works. It prints a good answer to the console, which (as far as know) shouldn't happen without return. I know it is written wrong and I will reply how it should be done but I want to be precise and include an answer why it worked. Here is the code:
#include <iostream>
using namespace std;
int add ()
{
int a,b,c, result;
cin >> a;
cin >> b;
cin >> c;
result=a+b+c;
}
int main()
{
cout << add();
return 0;
}
I would be grateful for an answer.
In some smart compilers it can run the code. but warning will be still there that function is expected to return integer but it is not returning anything.
but in environment like visual studio it will give the error and program will not be build.

Absurd output. Gives different output with and w/o debugging. Need expert intervention [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 5 years ago.
So here's the question. Find the output for the following code.
perform in c++
#include<iostream>
using namespace std;
int main()
{
int i=2;
cout<<i++<<i<<i++<<i;
cout<<i;
}
This concept is based on post/pre increment operator. Based on this concept I predicted the output as 23344. Like I expected it was correct when I tried debugging this code. But without debugging i am getting the output as 34244.
Is this even possible? BTW I tried this on Dev-C++ 5.11. Thanks :)
Your construction invokes Undefined Behavior.
See Undefined behavior in c/c++: i++ + ++i vs ++i + i++ and Why are these constructs (using ++) undefined behavior?
#include<iostream>
using namespace std;
int main()
{
int i=2;
//cout<<i++<<i<<i++<<i; // UB!
cout<<i++;
cout<<i;
cout<<i++;
cout<<i;
return 0;
}

Return value in C++ [duplicate]

This question already has answers here:
C++ return value without return statement
(6 answers)
Closed 6 years ago.
I am confused with the following output in C++
int add()
{
int c = 2+3;
}
int main()
{
int x = add();
cout << x;
return 0;
}
This prints 5.even if we do not write return statement.
How this is managed in C++.
Please help.
This is UB. You're right to be confused - this can work one day and fail the next. Don't rely on undefined behavior.
If you want to know why it works, it's because parameters & return values are passed on a data structure called stack (well - usually; sometimes passed in the same register). Similarly, most implementations use this same stack for locals. Therefore, the int in add will be located in the same place as where the return value is expected (by your specific implementation) and your implementation doesn't invalidate memory when your int there is destructed. But it's still destructed, it's still UB and it might break in any second.
As the comments wrote, you might turn on warnings to avoid this kind of error.

How does this function return a value when it shouldn't? [duplicate]

This question already has answers here:
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
(11 answers)
Closed 6 years ago.
This function returns a value even when it shouldn't.
#include<iostream>
using namespace std;
int foo(int a,int b)
{
if(a>b)
return a;
else if(a<b)
return b;
}
int main()
{
int x=7,y=7;
cout<<foo(x,y);
return 0;
}
The output is:
7
Also it produces proper output only on a GCC compiler (I used Dev C++). Turbo C produced garbage value.
Can someone explain how this happens?
The behaviour on not returning a value on all program control paths is undefined.
The compiler is allowed to do anything.
Didn't your compiler warn you of this? (GCC ought too, Turbo C possibly not on account of its age).

Functions that return const char* [duplicate]

This question already has answers here:
Do pointers to string literals remain valid after a function returns?
(4 answers)
Closed 8 years ago.
Although the following code does work, I do not know why. Please explain me.
#include <iostream>
using namespace std;
const char *f()
{
const char *p = "Hello!\n";
return p;
}
int main()
{
cout << f() << endl;
system("pause");
return 0;
}
From what I learnt, the 7 chars in f() are allocated on the stack (?), meaning that their memory will be released as soon as f() ends, however, the pointer returned by f() still points to a valid address in the application memory (meaning "Hello!" is successfully sent to the output). Why?
Same thing goes for
const int *f()
{
int i = 5;
const int *p = &i;
return p;
}
int main()
{
cout << *f() << endl;
system("pause");
return 0;
}
Can anyone shed some light on this?
What you´ve learned is correct, it´s not allowed to use local function variables
(ie. their used memory) anymore after the function ends.
If it works currently it´s nothing more than coincidence:
No other code has used this piece of memory in the meantime
for own things, so the old value is still there.
Your second code snippet causes undefined behaviour. The reason why it seems to work is, that you are lucky and the memory has not been overwritten.
However (as in the comment below mentioned) the first snippet is valid.