sepp2k 378 Practically a Master Poster

Even if you make abc global, it still doesn't work in Visual Studio 2015

Because your function is returning a copy of abc and that copy is a temporary object that goes out of scope at the sequence point, just as deceptikon explained.

returnValue seems to point to I'm not sure where, but clearly it's not pointing to whatever c_str() returned?

returnValue is exactly equal to the pointer retunred by c_str() - after all you just assigned it to that on the line before. However you called c_str() on the temporary object, not on abc and c_str() on the temporary object returns a different pointer than c_str() on abc, specifically it returns a pointer to temporary storage that gets freed when the temporary goes out of scope, which is why you see those results.

AssertNull commented: Good explanation +6
sepp2k 378 Practically a Master Poster
sepp2k 378 Practically a Master Poster

Note that using a different extension won't prevent people from opening the file in a text editor. It'll just stop a text editor from being the default application that will open when you double click on it in your file manager (unless the user then selects a text editor as the default for that extension).

sepp2k 378 Practically a Master Poster
<for loop> ::= for ( <expression> ; <expression>; <expression> ) <statement>

All three expressions in a for-statement are optional and from C99 onwards the first one may be a variable definition instead. Also note that the assignment specifically says that <statement> does not include composite statements (for whatever reason), so you need to cover that as well.

Other than that this looks okay.

sepp2k 378 Practically a Master Poster

Using your first definition account1.compareTo(account2) will call account2.name.compareTo(account1.name) and using your second definition it will call account1.name.compareTo(account2.name). So using the result of the comparisson will be the other way around and thus the sort order is reversed.

sepp2k 378 Practically a Master Poster

This isn't what's causing your syntax error, but Java doesn't have a type named sum nor do you define one anywhere in your prorgram (unless you defined it in a different file that you didn't show), so sum c is a type error (both on line 7 and line 8).

The compiler will probably complain about the (sum c)-> - it is non-terminated (no semicolon) and there isn't some value or method that the "pointer-to" operator references.

Java doesn't have pointers - -> is only used for lambdas (which would make (sum c) the argument list. But you're definitely right that a ; is missing. And there needs to be a function body after the ->. Also it makes no sense to have a lambda there.

sepp2k 378 Practically a Master Poster

The > operator is only defined for primitive types. To compare Comparable objects, use the compateTo method instead.

sepp2k 378 Practically a Master Poster

Thus, the compiler doesn't need to parse or read the whole file, before generating output

But here you're just saying that the compiler can start writing the .exe (or whatever) file before it's done parsing, right? By the time the compiler is done, it will still have parsed the whole file. It won't skip anything (barring preprocessor directives, which still need to at least read everything they're skipping and of course don't depend on user input in any way).

sepp2k 378 Practically a Master Poster

There's only a difference when you use the return value of the increment for something. So the two loops are completely equivalent.

sepp2k 378 Practically a Master Poster

Please post a compilable and runnable piece of code that reproduces your problem.

sepp2k 378 Practically a Master Poster

Any implementation will definitely read everything (well some languages have some kind of "stop here" token, which causes the impelementation to stop reading at that token, but in those case the stuff after would simply not be considered part of the program at all). Even if it did decide to skip, say, the body of an if-statement, it would still need to actually read it in order to know how far to skip.

A compiler will also never skip anything based on user input as the compiler can't possibly know what the user input will be (as the compiler is long done doing its job when the program actually runs). It might skip generating code if it can tell that a piece of code will never ever get executed (say if the programmer wrote something impossible like if(1==2)), but generally the code would still be parsed - just not translated to machine code.

An interpreter could skip based on user input, as interpreters actually run at the time as the program, but generally the only thing it'd skip is execution. That is if you have an if whose condition is false, the body obviously won't be executed. In most interpreters it would still be parsed though. However there are some interpreters, most notably shells, that actually do skip syntax analysis of any lines that do not get executed, that is after seeing an if with a false condition, it discards all lines until one is equal to fi (but, as …

sepp2k 378 Practically a Master Poster

If the shell is POSIX compliant, it will be able to correctly interpret what it gets back from the OS. So given that and given the fact that the OS will have gotten a value representing successful termination if main returned 0, returning 0 from main on success will cause shell scripts (running on POSIX compliant shells).

So I see no practical reason why you should not do that. Even if you do not personally care about that, I'd still say that "it makes no difference" is a gross overstatement at the very least.

sepp2k 378 Practically a Master Poster

if you want to go this way, you need to define carefully what this shell script language you're using does.

Fair enough. I was assuming a POSIX compliant shell (or presumably the windows command prompt, which I assume has the same semantics here).

Why bother?

Because shell scripts are the most obvious example of a case where it makes a huge difference whether an application exitted successfully or not.

My point is that the returned value meaning "success" from a given program is not mandated by the C standard to be the value zero. That's my point.

No, in fact I explicitly agreed with it at least once. I just don't see why that would matter when deciding whether to return 0; or return something_else; in main.

My point was that the main function that you define in your C code should always return 0 when it finished successfully because otherwise shell scripts and other applications will not work properly with your application. Is that what you disagree with?

Note that this discussion started with you saying that it did not matter which value was returned from main and me disagreeing with that statement. I never disagreed with your later statement that the value returned from main was not necessarily the same as the one returned to the OS, but the latter statement does not imply the former (because the value returned to the OS, even it is different from the one returned by …

sepp2k 378 Practically a Master Poster

Wait I totally confused myself. The way I originally wrote it was correct.

your-program || echo "Error"
So if your-program evaluates to zero, this will output "Error" on the screen?

No, if your-program does not evaluate to zero, this will output "Error" to the screen (assuming that your-program was compiled with a compliant C compiler).

The C standard does not mandate what a program should return in the event of success. It could return 0. It could return true. It could return false.

All that's true, but the C standard does mandate that the value returned should signify successful termination. As long as that's the case, the shell will get back the answer "yes" when it asks the OS "Did the program terminate successfully?". And if the shell does get that answer, it will not execute echo Error.

sepp2k 378 Practically a Master Poster

Is that what you meant to write?

Nope, removed the mistaken "not".

sepp2k 378 Practically a Master Poster

No, it's not. The C standard says that if main returns 0, the program should indicate to the OS that it was successful. But if it did that your-program || echo "Error" would not print "Error" as the shell asks the OS whether your-program exitted successfully and only executes echo "Error" if that was not the case.

Therefore if "Error" is printed, the program must not have done what the C standard said it should do.

sepp2k 378 Practically a Master Poster

If by "false" you mean "was not successful", I disagree.

By false I meant that it'd go into the else of an if, the alternative of an || or that it wouldn't go into the right side of an &&. That is if your main returns 0 and your-program || echo "Error" prints "Error", your compiler is non-complying.

The OS might ultimately get back the string "Beans on toast" from the program to indicate success. The C standard makes no such mandate.

Sure, that's all fine as long as it ultimately causes the if to go into the then-branch and not the else-branch.

sepp2k 378 Practically a Master Poster

If a shell script is relying on the return value of a program, the person who wrote that shell script should read the documentation and learn what the returned values mean.

If it relies on the exact numeric value, sure. But if a shell script does something like the_program && some_other_program or if the_program; then; ...; else; error_handling_code; fi, that should not require consulting the documentation.

Not to mention that there are various tools (like most IDEs, build tools, test tools etc) that work with arbitrary programs and will treat non-zero exit codes as failures. In that case consulting the documentation would of course be impossible.

This is no guarantee that what you'll get back at the operating system is the number zero, though - that's completely up to the implementation.

However it is a guarantee that what we give back to the operating system indicates success. If we have a compiler+OS combination where a program with return value 0 is treated as false in a shell script, that'd be a violation of the standard.

sepp2k 378 Practically a Master Poster

In the program Why you used 0 in return 0 ;

The return value of main is the program's exit code. If it is 0, that means that the program terminated successfully. A different return value means that the program failed. This distinction matters most in shell scripts:

if my_c_program bla
then
    echo "main() returned 0"
else
    echo "main() returned something other than 0"
fi
# Or:
my_c_program && echo "This will only get printed if main() returned 0"
my_c_program || echo "This will only get printed if main() returned something other than 0"

The exit code will also be available in the variable $?, which a shell script (or a normal user) can use to see the exact value that was returned, which might tell what went wrong (assuming the program has multiple meaningful error values that are explained in the documentation).

When your program is invoked by another program, that program can also see your exit code. For example most IDEs will inform you that your program has exitted abnormally if you run it from the IDE and it returns a non-zero value.

if you use a in return a; then it also print the correct output but why ?

The return value does not affect the output of the program in any way.

The value of that int makes no difference.

As I explained above it makes a lot of difference to shell scripts and any tool that queries …

sepp2k 378 Practically a Master Poster

2147483647 is the largest number that an int can store. When you convert it to float, it becomes 2147483648.0 due to floating point accuracies. When you convert that back to int, you'd get 2147483648, except that that's too large to fit into an int. So instead you get an overflow, resulting in -2147483648, which is the smallest number an int can store - and thus the first number you get after an overflow.

If you used a long instead of an int for backAgain, it would have the value 2147483648 as (possibly) expected.

I assume there was some data loss when float was explicitly casted into int .

There was a loss of precision when the int was casted to float (note that this cast can be lossy even though it is implicit - this may perhaps be considered improper language design). There was then additionaly an overflow when casting back.

ravi_14 commented: Lucid and to the point! Thanks a lot! +1
sepp2k 378 Practically a Master Poster

Your question seems to be missing some words. Did you mean "After returning true, does the for loop continue?" If so, the answer is no. When the return statement is reached, the control flow returns to the call site.

sepp2k 378 Practically a Master Poster

but we can't access any character from char pointer with loop like str[0]. str[0] prints the whole string till last character.

That's not true. str[0] will give you the character 'T' in your example, str[1] will give you 'h' and so on.

sepp2k 378 Practically a Master Poster

When you don't specify the size of an array, the size is inferred from the initializer. So when you write int arr[] = {1,2,3}, that's the same as int arr[3] = {1,2,3}. Likewise char formula[] = {'\0'} is the same as char formula[1] = {'\0'} and equivalently char fomula[] = "" is the same as char formaula[1] = "".

So you're defining an array of size one. You're then writing into that array using cin >> formula. This will write more than one character into the array, meaning you're writing out of bounds. This invokes undefined behavior, possibly overwriting other variables' memory and/or causing a crash.

sepp2k 378 Practically a Master Poster

Syntax errors come with a line and column number as well as some indiciation of what's missing (or what's there that shouldn't be). So to find a syntax error you should look around the given line and column for anything that might fit the error message.

If the message is about a missing or superfluous }, it indeed makes sense to indent your code to find it (in fact that always makes sense if for no other reason than that we won't get a migraine when reading your code).

sepp2k 378 Practically a Master Poster

It'd have helped us if you had described in what way the code did not behave as expected, but your problem is that you access the matrix out of bounds (the matrix can hold 2x2 items, but you're trying to store 3x3).

Also you're printing "1th" and "2th" when the correct forms would be "1st" and "2nd" (also "0th" isn't very pretty, you should probably add one the index when displaying it, so that the first item is referred to as the first, rather than the zeroth).

tobyITguy commented: Exactly. Descriptions are important +1
sepp2k 378 Practically a Master Poster

Oh, I seem to have missed a question earlier:

Please explain: why do we need to have base class' at least one virtual function? Why is it so?

Technical reasons. Namely to implement dynamic_cast, you need some kind of metadata associated with an object in order to tell whether the object has the correct type. Classes without virtual functions are not supposed to have any overhead like metadata (both for C compatibility and performance reasons), so they don't have the necessary metadata. Classes with virtual functions need metadata anyway (namely the vtable), so adding the information for the type check makes little difference (if it even needs anything besides the vtable - I'm not sure on that one).

sepp2k 378 Practically a Master Poster

Programmer *pProg = (Programmer *)&employee;

A downcast is valid if the object to which the pointer points actually is of the type to which you cast.

Secondly, Can you explain this line?

What did you not understand about that line?

sepp2k 378 Practically a Master Poster
Base *pb = dynamic_cast<Base*>(&d);

This is an upcast. Using dynamic_cast here is pointless as the cast is always valid. You can and should just write it as Base *pb = &d.

Derived *pd = dynamic_cast<Derived*>(&b);

Since b is an actual Base object, not a Derived object, this downcast is invalid and will throw an exception.

Programmer *pProg = (Programmer *)&employee;

This is the same invalid downcast, but since you're not using dynamic_cast, it invokes undefined behavior rather than throwing an exception.

sepp2k 378 Practically a Master Poster

I am not to properly understand why, and when we have to dynamic cast.

Strictly speaking, you don't ever have to use dynamic_cast. You can use dynamic_cast when the castee is a pointer or reference to a class that contains at least one virtual member (that's what's meant by the pointer being polymorphic).

The reason that you should use dynamic_cast over static_cast (when downcasting) is that dynamic_cast will throw an exception when the pointed-to object does not actually have the correct type, whereas static_cast would invoke undefined behavior in that case.

sepp2k 378 Practically a Master Poster

Can you tell me onw thing why we have to commit?

To apply changes from the workspace to the repository.

I read somewhere that workspace is different from the local repository. How?

The workspace contains one specific version of your files. The repository (i.e. the .git folder) contains a complete history which keeps track of all changes you ever commited with branches and everything.

I know there is one .git hidden folder. I checked into that. There is no copy of testfile1.txt present.

There is, it just doesn't exist as a file as such. Rather you can think of the repository as a database which keeps track of all actions you ever committed (like creating files, changing, moving or deleting them). It contains all information necessary to undo and redo any change you every committed as well as combining changes from different branches.

Your workspace on the other hand only contains the contents of the files right now.

Do I have two copies of the same file in git system?(one i am editing and one i over-write after commoting) ? Explain.

You can sort of think of it as having one copy for each version that ever existed. Like if you create a file with the contents "bla", commit it, change it to "blablubb", commit it again and then change it to "blobbel", your workspace will contain a file with the contents "blobbel". Your repository will (sort of) contain the versions containing …

sepp2k 378 Practically a Master Poster

If a file has never been added, it is untracked. Untracked files are not affected by anything you do with git (like switching branches).

One way of looking at it is that, until you added the file, the file did not exist in any branch. Instead it existed in the directory and it kept existing there no matter which branch you were in because it was completely independent from git. Once you added the file, it became tied to git and now existed in some branches only, so its existence would depend on which branch you're in.

sepp2k 378 Practically a Master Poster

usually describing its time complexity, though in principle it could be used to describe space complexity as well.

No, you're probably thinking of Big-Oh (which is most often used to describe time, but can also be used to describe space - or anything else). P is specifically the set of problems that, for some constant c, can be solved in O(n^c) time on a DTM (same for NP and NTMs). If you want the same thing for space, there's the PSPACE class, which is a very different class. P and PSPACE can not be used interchangeably.

sepp2k 378 Practically a Master Poster

NP means a NTM can solve it in polynomial time (or equivelantly that a DTM can verify the result in polynomial time). Note that NP is a superset (possibly, but not necessarily, a proper superset) of P, meaning that everything in P is also in NP.

A problem X being NP-hard means that every problem in NP is reducible in polynomial time to X. Intuitively this means that X is at least as hard as every problem in NP. Note that this does not mean that X itself must be in NP.

A problem is NP-complete if it is both NP-hard and in NP.

sepp2k 378 Practically a Master Poster

Your programm will not be .net dependent if you choose "Win32 console application", only if you choose "C++/CLI".

The name "Win32 console application" may suggest that will depend on the Win32 API, but that's not actually true (unless you specifically use functions from the Win32 API).

sepp2k 378 Practically a Master Poster

Is there no way to program standard C++ CLI applications without having this ".NET CLR"? To create C++ code that will work for general purpose, instead for Windows only?

It is possible to write standard-compliant, cross-platform C++ code, though VS doesn't make that particularly easy for you. It is not possible to create C++/CLI applications that don't rely on .net because C++/CLI is a separate language from C++ and it's closely tied to .net.

Note that the "CLI" in "C++/CLI" stands for "Common Language Infrastructure", not "Command Line Interface". So if you want to create a command line application in C++, "C++/CLI" isn't the option you want to pick in the wizard (as you seem to have realized already).

Worked, thank you for your solutions everybody.

Note, that the code you have still won't compile with compilers other than VS's. To make it compile everywhere:

  • Disable pre-compiled headers in your project settings and remove the include of stdafx.h.
  • There is no type called __int64 in the C++ standard (or in any compiler besides VS's). From C++11 onwards you can use either long long (which will have at least 64 bits) or, if you need it to be exactly 64 bits, int64_t from the <cstdint> header. At least long long has been supported by the majority of compilers already long before C++11, so it shouldn't cause compatibility problems with older compilers.

PS: You don't need the <sstream> header for anything you did in your code.

sepp2k 378 Practically a Master Poster

no instance of overloaded function "System::Console::WriteLine" matches the argument list argument types are: (const std::string)

I've never used C++/CLI, but it looks like std::string is a distinct type from System::String and presumably Console::WriteLine only works with the latter as it is a .net method and std::string is a C++ class.

Presumably C++/CLI offers some way to convert between the two string types, but I imagine in this case it'd be easiest to just either only use C++ strings and C++ IO functions or .net strings and .net IO functions.

Anyway, the problem here is that the System class is not included.

No, it's not. using namespace System; just means that you're then allowed to write Console::WriteLine instead of System::Console::WriteLine. It does not change for which types the WriteLine method has overloads.

sepp2k 378 Practically a Master Poster

Whether you can parse each line individually depends on the language. I'd say in most languages, you'd need to parse the program as a whole. But yes, a simple (as in: non-JITing) interpreter generally consists of two phases: parsing and execution.

I suppose the code needs instructions on how to execute each line ?

For each type of instruction that exists in your language, the interpreter needs to contain code that can execute that kind of instruction. If that's what you mean, then yes, absolutely.

sepp2k 378 Practically a Master Poster

If you know how many elements you're going to add to the vector (or you at least have a reasonable upper bound), you can also use reserve to reserve the proper amount of memory up front, preventing reallocations. Then you'd have exactly one move constructor call per push_back and no calls of the copy constructor.

sepp2k 378 Practically a Master Poster

The controller variable is not defined within the counter method. You need to either pass it as a parameter or make it a member of the object (by doing self.controller = controller in the constructor) and then access it as self.controller instead.

In the future please include any error messages you get with your code (including line numbers and such). This makes it much easier for us to find the problem.

sepp2k 378 Practically a Master Poster

Is {(1,1), (2,2), (3,3)} symmetric? transitive? Yes! Yes!

Obviously I'm not your grader, but I'd expect that you need to give some explanation along with your answers to get a full score. Other than that you are correct.

Why is R = {(1,2), (2,3), (1,3), (2,1)} not transitive? Because (1,1) and (2,2) are missing.

Again, the answer would be better if you explained why those would be needed for it to be transitive, but is otherwise correct.

So, is there a question here? Or are you just showing off?

The question's in the title (which admittedly is bad style): "Is this correct or not"

Also, I wouldn't call the matrix symmetric

It's not a matrix, it's a set of pairs that represents a relation.

sepp2k 378 Practically a Master Poster

gcc produces a binary executable, not a shell script. To run it, type ./main.out.

CattleOfRa commented: Really stupid of me... thank you so much +0
sepp2k 378 Practically a Master Poster

EOF is not captured in the char data type. EOF is represented as an int with the value -1. Now you say "why can't we just use a char with the value -1 - isn't that the same thing?". And the answer is: because, depending on the encoding, there are already 256 valid character values. So the char -1 (or 255 depending on whether char is signed or unsigned) already represents a valid character - it can't also represent EOF.

What getchar does is it represent the 255 valid character values as ints from 0 to 255 and it represents EOF as -1. So 255 and -1 are two very different results.

sepp2k 378 Practically a Master Poster

No a char value can not be larger than what fits inside a char. However what getchar returns does not have to be a char value. It could also be EOF.

Except for the missing &, your scanf line is perfectly fine.

When scanf reaches the end of file (or any unexpected input), it will return a number that is less than the expected one. It will not write anything into the given pointers. Therefore there is no need for an EOF value with scanf.

sepp2k 378 Practically a Master Poster

It looks like the Ribbit class does not have a userid= method - presumably because you did not define one and the corresponding table does not have a userid column either.

sepp2k 378 Practically a Master Poster

You need to #include <stdio.h> to get the declaration of fopen. As it is now you're implicitly declaring fopen in a way that is incompatible with its definition. You should be getting a warning about that (and in C99 and later you should instead be getting an error that you're using a function without a declaration).

Once you do that, you should be getting another warning that you're implicitly converting the result of fopen from FILE* to int. That's because fopen doesn't read anything from the file nor does it return an int. fopen opens the file and then returns a file pointer. That file pointer can then be given to other file IO functions (like fread, fwrite, fgets, fscanf, fprintf etc.), which will actually read from or write to the file. Once you're done working with the file, you need to close it by passing the file pointer to fclose.

So no, you're not currently doing it correctly. The number you're printing is simply the numeric value of whichever pointer was returned by fopen. It has nothing to do with the contents of the file.

sepp2k 378 Practically a Master Poster

Something else to consider, using the String.IndexOfAny method will shorten your code considerably

And, perhaps more importantly, improve the runtime from being quadratic in the worst case to being linear (in the length of the string).

overwraith commented: That's a good point. +2
sepp2k 378 Practically a Master Poster

is the + operation returning a new big integer object?

Yes, exactly.

sepp2k 378 Practically a Master Poster

You're right, that when you do something = new Something(); that basically assigns a "very safe pointer" (a.k.a. reference) to something. In fact when you do something = anything;, you're assigning a reference.

Also note that x += y is just a shortcut for x = x + y;. So when you do:

BigInteger current = enumerable1.getCurrent();
current += enumerable2.getCurrent();

You're assigning a reference to current on the first line and then assigning another reference on the second line. In C, the equivalent would look something like this:

BigInteger* current = getCurrent(enumerable1);
current = add_big_integer(current, getCurrent(enumerable2));

Where add_big_integer has the signature BigInteger* add_big_integer(BigInteger*, BigInteger*). The important thing here is that the second line is not:

*current = *add_big_integer(current, getCurrent(enumerable2));

Assigning to a non-ref/out variable in C# never changes the object that the variable currently refers to - it simply makes it refer to something else. In order to change the object itself, you either need to assign to one of the object's properties (or variables if it has any public ones) or call a mutating method on it (i.e. method that changes the state of the object).

However the BigInteger class does not have any mutating methods, so you simply can't do this.

sepp2k 378 Practically a Master Poster

How long are the strings you enter? If the first string has more than 2 characters, your first call to gets overflows your array. Likewise your second call to gets overflows if the second string entered is 2 * sl characters long or longer.

Either way the call to strcat will overflow str unless str2 is the empty string.

Further the arguments given to strcpy must not overlap, so your call to strcpy always invokes undefined behavior. What is the goal of that call?

sepp2k 378 Practically a Master Poster

Funny, I remember Zork being longer and having a much more sophisticated parser.

In all seriousness though, this is not a good example of how to program a Zork-like game. Not only does it exhibit bad coding practice in general (like using a variable with a completely meaningless name holding magic numbers whose semantics seem completely arbitrary), its whole approach is not suitable to implement a game like this.

I'm sorry if this is your code and this sounds harsh, but no one should take this code as an inspiration to learn how to program.