I saw this piece of code today:
while(scanf("%d %d",&x,&y),x||y)
{
....
From what I've understand, it enters the loop if some of the values (x or y) is true.
Since the scanf docs says:
On success, the function returns the number of items of the argument
list successfully filled. This count can match the expected number of
items or be less (even zero) due to a matching failure, a reading
error, or the reach of the end-of-file.
I have rewritten the code to:
while(scanf("%d %d",&x,&y) >= 1)
{
....
But on an online programming challenge site the first while works, the second fails.
Am I right on my assumptions ? What are the differences between this two pieces of code?
(I am tagging as C++, because I have tested in C++ 4.8.2 - GNU C++ Compiler)
scanf returns the number of arguments it matches, but the first code fragment throws out that result and just checks to see if either x or y is true. The second fragment returns that you matched at least one integer, regardless of value.
Consider the input "0 0". In the first case, scanf() returns 2, but x || y returns false. In the second case, your conditional is true.
The first code gives while the result of x||y, this is correct
However, the second code compares the return value of scanf and 1, and then gives while the comparing result.
run this code and you'll be clear.
#include<stdlib.h>
#include<iostream>
using namespace std;
int main()
{
int x, y;
cout<<(scanf("%d %d", &x, &y), x||y)<<endl;
cout<<(scanf("%d %d", &x, &y))<<endl;
return 0;
}
Related
Code in case if the image not is visible.
#include <stdio.h>
int fun(int n)
{
if(n=4)
return n;
else
return 2*fun(n+1);
}
int main()
{
printf("%d", fun(2));
}
This is the code snippet and the output is given as 4 by the professor.
How is the output correct?
Is it possible that n=4 is assigned in the 'if-else' statement as the assignment operator is correct, but the "if" condition will not work as the syntax is wrong and the output will be directly given as 4.
The answer is correct, and there aren't any syntax errors.
= is an assignment operator, and in C/C++, (n = 4) is a valid expression that evaluates to true as long as the expression is not (n = 0), because n will then be considered as false by C. Note that in C/C++, 0 is false and everything else is true.
Hence, if (n = 4) is perfectly valid and always evaluates to true. Of course, in the process, there will also be an assignment involved.
Thus, what happens in the code above is that
the integer n is assigned the value 4 in n = 4
(n=4) as an expression returns true.
return n (4).
So the answer is 4.
Assignment in a if-else statement is valid syntax and the branching will depend on the value of n.
Example:
#include <iostream>
int main() {
int n = 2;
if (n = 0) {
std::cout << "Never printed\n";
}
if (n = 4) {
std::cout << "Always printed\n";
}
return 0;
}
Compiler explorer: https://godbolt.org/z/fEYPcq
You should use == operator to make a confront between two compatible values.
if(n = 4) assign 4 to n and then the if statement is always true. So the return value will always be 4.
"Is it possible that n = 4 is assigned in the if-else statement as the assignment operator is correct, but the if condition will not work as the syntax is wrong....?"
The syntax is not wrong and the if condition does work. It is perfectly valid. And yes, the assignment is also valid/correct.
With if (n = 4) you assign the value of 4 to the function-local variable n, although this makes less sense since n is a parameter and is meant to be feed with different values at each call to the function fun().
But I guess the intention of your professor is exactly to demonstrate this trickery, so it makes sense.
So the value of n is not 2 anymore; It is 4.
This is a valid expression for the if condition and evaluates to 1/true since the value/expression to be assigned is or does not evaluate not 0.
Usually a compiler will warn you about doing so nonetheless to avoid any undesired result here by suggesting optional parentheses around the assignment like: if ((n = 4)).
Clang:
warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
GCC:
warning: suggest parentheses around assignment used as truth value [-Wparentheses]
If you explicitly want to remove these warnings, use the -Wno-parentheses flag. But it is recommended not to do so.
Since the if condition is true, it doesn't get to the recursive part in the else condition and the function fun immediately returns n which is 4.
So is the return value of 4 displayed by the call to printf() in the caller.
My favorite to remember that is this:
int war = false;
if (war = true) { launch nuke; }
Credits go to WTP.
Maybe you'll catch the joke. ;-)
Consider the code:
#include<iostream>
using namespace std;
int refcube(double &ra)
{
ra*=ra*ra;
return ra;
}
int main()
{
auto x=2.0;
cout<<"cube of "<<x<<" is "<<refcube(x)<<endl;
return 0;
}
The output is:
cube of 8 is 8
Why the value of x at the first is displaying as 8 instead of 2?
Because evaluation order is not specified.
The compiler may generate the code to call refcube(x) and compute its value before or after generating the code to obtain the value of x, for output to std::cout.
Your compiler chose to compile this C++ code as calling refcube(x) first, and then by evaluating x.
The C++ language specification spends quite a few pages on the topic of "sequencing", which (very loosely speaking) specifies the evaluation order. To make a long story short, in this example, x is not sequenced with respect to refcube(x), in the expression that generates the output to std::cout, and such a compiler is free to compile either portion of the expression first.
I was writing factorial using tail recursion and I have a question here. My original function looks like this
Code snippet A
#include <stdio.h>
int main(void)
{
int n = 0;
printf("Enter number to find factorial of : ");
scanf("%d",&n);
printf("fact == %d\n",fun(n,1));
return 0;
}
int fun(int n, int sofar)
{
int ret = 0;
if(n == 0)
return sofar;
ret = fun(n-1,sofar*n);
return ret;
}
However, even if I do not use return, it still works. This does not make perfect sense since I am returning the value only in the base case. Say if n==5, then 120 would be returned at the base case. But what gets returned from 4th invocation back to the 3rd invocation cannot be predicted since we are not explicitly specifying any return unlike in Code snippet A.
Code snippet B
int fun(int n, int sofar)
{
int ret = 0;
if(n == 0)
return sofar;
ret = fun(n-1,sofar*n);
}
I am thinking the above works because of some kind of compiler optimization ? Because If I add a printf statement to Code snippet B, it does not work anymore.
Code snippet C
int fun(int n, int sofar)
{
int ret = 0;
if(n == 0)
return sofar;
ret = fun(n-1,sofar*n);
printf("now it should not work\n");
}
Probably the printf causes something to be removed from the stack? Please help me understand this.
Not returning a value from a fuction which should return a value is undefined behavior.
If it works by any luck then it's not an optimization but just a coincidence given by how and where these automatic allocated values are stored.
One could speculate about the reason why this works, but there is no way to give a definitive answer: reaching the end of a value-returning function without the return statement and using the return value is undefined behavior, with or without optimization.
The reason this "works" in your compiler is that the return mechanism used by your compiler happens to have the right value at the time the end of function is reached. For example, if your compiler returns integers in the same register that has been used for the last computation in your code (i.e. ret = fun(n-1,sofar*n)) then the right value would be loaded into the return register by accident, masking undefined behavior.
It works because the return value is almost always stored in a specific CPU register (eax for x86). This means that is you don't explicitly return a value, the return register will not be explicitly set. Because of that, its value can be anything, but it is often the return value of the last called function. Thus, ending a function with myfunc() is almost guaranteed to have the same behavior as return myfunc(); (but it's still undefined behavior).
Here is the reason 'something' is calculated.
the call to printf() has a returned value (very rarely used) of the number of characters printed (including tabs, newlines, etc)
in the 'C' code snippet, printf() is returning 23.
'int' returned values are always returned in the same register.
The printf() set that register to 23.
So, something is returned, nothing was removed from the stack.
The reason why it seems to work in B is because the return value is most likely passed in a register on your architecture. So returning through all the layers of recursion (or if the compiler optimized the whole thing into iteration) nothing touches that register and your code appears to work.
A different compiler might not allow this to happen or maybe the next version of your compiler will optimize this differently. In fact, the compiler can remove most of the function because it is allowed to assume that since undefined behavior can't happen it must mean that the part of the function where the undefined behavior seems to happen will never be reached and can be safely removed.
Possible Duplicate:
"compare" definition
Differences between C++ string == and compare()?
As the pages said "compare" simply compares two strings and returns an integer 0,1,-1
but in my test cases (when a=100 and b=1) it returns 2 also.
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
#include<stdlib.h>
using namespace std;
int main()
{
string a,b,ans;
//for(;;)
{cin>>a>>b;
cout<<a.compare(b)<<"\n\n";}
return 0;
}
Also I am not able to understand how the function is comparing two strings (is it only number of digits)
for test cases like a=10^n b=1 it returns n.
It's impossible to speak for "the pages". You can probably find a Youtube video that will make any claim about anything, so that's not a good basis to go on.
Instead, let's turn to the language standard. It says, in [string::compare]:
basic_string::compare: int compare(const basic_string& str) const noexcept;
Effects: [...] compares the two strings by calling traits::compare(data(), str.data(), rlen).
Returns: The nonzero result if the result of the comparison is nonzero. [...]
(There's an additional rule about first comparing the string lengths, which I'm omitting here.)
So then, traits::compare is what we need. The traits need to satisfy the "Character trait requirements", which say:
yields: 0 if for each i in [0,n), X::eq(p[i],q[i]) is true; else, a negative value if, for some j in [0,n), X::lt(p[j],q[j]) is true and for each i in [0,j)
X::eq(p[i],q[i]) is true; else a positive value.
In other words, string::compare returns a negative value, zero, or a positive value respectively to represent lexicographic less-than, equal or greater-than. No actual result values are prescribed, only their sign.
A decent web reference should get this right, though, so you if you know how to find a good source of information, you don't always have to dig through the standard yourself.
If there are non-number characters in a string and you call atoi [I'm assuming wtoi will do the same]. How will atoi treat the string?
Lets say for an example I have the following strings:
"20234543"
"232B"
"B"
I'm sure that 1 will return the integer 20234543. What I'm curious is if 2 will return "232." [Thats what I need to solve my problem]. Also 3 should not return a value. Are these beliefs false? Also... if 2 does act as I believe, how does it handle the e character at the end of the string? [Thats typically used in exponential notation]
You can test this sort of thing yourself. I copied the code from the Cplusplus reference site. It looks like your intuition about the first two examples are correct, but the third example returns '0'. 'E' and 'e' are treated just like 'B' is in the second example also.
So the rules are
On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.
According to the standard, "The functions atof, atoi, atol, and atoll need not affect the value of the integer expression errno on an error. If the value of the result cannot be represented, the behavior is undefined." (7.20.1, Numeric conversion functions in C99).
So, technically, anything could happen. Even for the first case, since INT_MAX is guaranteed to be at least 32767, and since 20234543 is greater than that, it could fail as well.
For better error checking, use strtol:
const char *s = "232B";
char *eptr;
long value = strtol(s, &eptr, 10); /* 10 is the base */
/* now, value is 232, eptr points to "B" */
s = "20234543";
value = strtol(s, &eptr, 10);
s = "123456789012345";
value = strtol(s, &eptr, 10);
/* If there was no overflow, value will contain 123456789012345,
otherwise, value will contain LONG_MAX and errno will be ERANGE */
If you need to parse numbers with "e" in them (exponential notation), then you should use strtod. Of course, such numbers are floating-point, and strtod returns double. If you want to make an integer out of it, you can do a conversion after checking for the correct range.
atoi reads digits from the buffer until it can't any more. It stops when it encounters any character that isn't a digit, except whitespace (which it skips) or a '+' or a '-' before it has seen any digits (which it uses to select the appropriate sign for the result). It returns 0 if it saw no digits.
So to answer your specific questions: 1 returns 20234543. 2 returns 232. 3 returns 0. The character 'e' is not whitespace, a digit, '+' or '-' so atoi stops and returns if it encounters that character.
See also here.
If atoi encounters a non-number character, it returns the number formed up until that point.
I tried using atoi() in a project, but it wouldn't work if there were any non-digit characters in the mix and they came before the digit characters - it'll return zero. It seems to not mind if they come after the digits, for whatever reason.
Here's a pretty bare bones string to int converter I wrote up that doesn't seem to have that problem (bare bones in that it doesn't work with negative numbers and it doesn't incorporate any error handling, but it might be helpful in specific instances). Hopefully it might be helpful.
int stringToInt(std::string newIntString)
{
unsigned int dataElement = 0;
unsigned int i = 0;
while ( i < newIntString.length())
{
if (newIntString[i]>=48 && newIntString[i]<=57)
{
dataElement += static_cast<unsigned int>(newIntString[i]-'0')*(pow(10,newIntString.length()-(i+1)));
}
i++;
}
return dataElement;
}
I blamed myself up to this atoi-function behaviour when I was learning-approached coding program with function calculating integer factorial result given input parameter by launching command line parameter.
atoi-function returns 0 if value is something else than numeral value and "3asdf" returns 3. C -language handles command line input parameters in char -array pointer variable as we all already know.
I was told that down at the book "Linux Hater's Handbook" there's some discussion appealing for computer geeks doesn't really like atoi-function, it's kind of foolish in reason that there's no way to check validity of given input type.
Some guy asked me why I don't brother to use strtol -function located on stdlib.h -library and he gave me an example attached to my factorial-calculating recursive method but I don't care about factorial result is bigger than integer primary type value -range, out of ranged (too large base number). It will result in negative values in my program.
I solved my problem with atoi-function first checking if given user's input parameter is truly numerical value and if that matches, after then I calculate the factorial value.
Using isdigit() -function located on chtype.h -library is following:
int checkInput(char *str[]) {
for (int x = 0; x < strlen(*str); ++x)
{
if (!isdigit(*str[x])) return 1;
}
return 0;
}
My forum-pal down in other Linux programming forum told me that if I would use strtol I could handle the situations with out of ranged values or even parse signed int to unsigned long -type meaning -0 and other negative values are not accepted.
It's important upper on my code check if charachter is not numerical value. Negotation way to check this one the function returns failed results when first numerical value comes next to check in string. (or char array in C)
Writing simple code and looking to see what it does is magical and illuminating.
On point #3, it won't return "nothing." It can't. It'll return something, but that something won't be useful to you.
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.