Narue 5,707 Bad Cop Team Colleague

Note that in this case there is in fact a "useful value" returned, which is 5.

Just how is 5 useful? Sure, it's the correct type, but the value itself is completely unpredictable garbage.

Bug? Error in the text?

Error in reading the text. You apparently read it as "I can define a function that claims to return a value, not return a value, and magic happens". The actual meaning is that functions are not required to return a value. This is as opposed to languages that differentiate between procedures (which don't return a value in all cases) and functions (which do return a value in all cases).

Note that the first chapter is intentionally simplified, so many of the nuances will be left out. In practice, functions with a return type of void cannot return a value (you can use an empty return statement or fall of the end) while functions with any other return type must return a value or risk undefined behavior.

Salem commented: rep++ +17
Narue 5,707 Bad Cop Team Colleague

I just read in K&R that a function, even if not defined as void, need not return a value.

What page? From memory, the only place where K&R makes such a grievous mistake is in the beginning tutorial with the initial definitions of main. However, that's a pedagogical decision that they clearly explain a bit later.

Why is the function returning 5?

The usual explanation is that it's undefined behavior and anything could happen. But to speculate about what's happening in your case, 5 is coming from whatever was in already in the location where return values are stored. As an illustrative example, let's consider a hypothetical compiler that uses a hidden pointer parameter for return values. If you return a value it might look like this after compiler translation:

void power(int *__$retv, int x, int y)
{
    int i, total = 1;

    for (i = 0; i < y; i++)
        total *= x;

    *__$retv = total;
}

void main(int *__$retv)
{
    int __$power$retv;
    int __$printf$retv;

    power(&__$power$retv, 2, 5);
    printf(&__&printf&retv, "%d\n", __$power$retv);

    *__$retv = 0;
}

Without a return statement to translate, the power function would look more like this:

void power(int *__$retv, int x, int y)
{
    int i, total = 1;

    for (i = 0; i < y; i++)
        total *= x;
}

Notice how *__$retv is never set, and the hidden temporary in main is a local variable without any default initialization. This means that if you don't provide a return value in this …

Narue 5,707 Bad Cop Team Colleague

Subscriptions and such can be edited from your control panel, but the specifics depend on exactly what you're thinking of as the subscription. So, unsubscribe from what, exactly?

Narue 5,707 Bad Cop Team Colleague

Please take this little spat to PM.

Steve, if you have a specific complaint then send me a PM with the details and I'll take a look. However, concerning the Viruses, Spyware and other Nasties forum, we've recently tightened up the rule set. Due to the potential damage to OP computers, the mods have permission to strictly moderate posts based on content that doesn't otherwise break Daniweb's rules.

Since you seem to be one of the first casualties of this new policy, your feedback is most welcome.

Narue 5,707 Bad Cop Team Colleague

Your question is: does prefixing this to member access have a performance cost? The answer is no, it should not.

Narue 5,707 Bad Cop Team Colleague

But shouldn't I clear out the input stream before I use cin again?

How do you know that it needs to be cleared? What if the next request for input corresponds to whatever is already in the stream? I can type "123 4.5 booga" all on one line and the following code will work perfectly:

#include <iostream>
#include <string>

int main()
{
    int a;
    double b;
    std::string c;

    std::cin>> a;
    std::cin>> b;
    std::cin>> c;
    std::cout<< a <<'\n'<< b <<'\n'<< c <<'\n';
}

There's no need to clear the stream when it's properly formatted in the first place.

since cin.get() returns an int,what sense does the while condition make?

The condition is equiavelent to while (cin.get() != 0) . However, since it's rather difficult to get cin.get() to return 0, that loop is nonsensical.

and also,when I entered 'h' for x,the while loop ran twice,collecting the 'h' and '\n',but after that,I was again prompted to enter something.
Why so?What is happening?

How did you plan on typing a character with the value 0?

And also,why have you used the condition,while(cin.get()!='\n')?
Is there a problem if the '\n' is collected from the stream?Whats the harm?

That method of clearing the stream relies in line-oriented interactive input. The user will never enter more than a single line at a time, so when you detect a newline character it corresponds to the end of input. Trying to read further would block for more input and defeat the purpose …

Narue 5,707 Bad Cop Team Colleague

but if i do it like in the number 2...is it also right?

No. Might I recommend dropping down a level and learning basic programming through pseudocode? Your C is just awful, and not understanding the the fundamentals won't help.

Narue 5,707 Bad Cop Team Colleague

Replace ++x; with scanf("%d", &x); and your logic is reasonably sound. Otherwise it's broken because the loop will never end[1].


[1] It will end, but not in a well-defined way.

Narue 5,707 Bad Cop Team Colleague

Don't see anything funny

Funny as in unusual, not funny as in ha-ha. The suggestion is that by using a quote without specifying whom you're addressing, you're replying to the person being quoted. So it's not unreasonable for that person to assume you're referring to them. However, it is unreasonable to get your panties in a twist when that person further replies to you as if you were referring to them, which you apparently did here:

So please read more carefully next time before making silly accusations!

Just FYI.

Narue 5,707 Bad Cop Team Colleague

You sound incredibly lazy. Seeing as this is a trivial program, try it yourself first.

Narue 5,707 Bad Cop Team Colleague

If you don't supply an explicit return type for a function, the compiler assumes that you meant int. So your declaration is:

void add_end(struct node **q);

And your definition with the implicit int added is:

int add_end(struct node **q)
{

That's the mismatch. Place a void explicitly in the definition (a good trick is to copy/paste the declaration when creating a definition) and all will be well:

void add_end(struct node **q)
{
Narue 5,707 Bad Cop Team Colleague

If you do not want to remove the names of the parameters:

#include <iostream>
    #define UNREFERENCED_PARAMETER(x) x

    int main(int argc, char* argv[])
    {
    UNREFERENCED_PARAMETER(argc);
    UNREFERENCED_PARAMETER(argv);
    std::cout<<"Hello, world!\n";
    }

That's hideous. I fail to see how any of these workarounds are better than simply not defining unused parameters in the first place.

Narue 5,707 Bad Cop Team Colleague

a> What is static library? What is dynamic library?

What is google?

b> What is the difference between c code, object code and exe file??

C code is human readable source code. Object code is C code compiled into machine readable instructions. EXE files are directly executable object code.

c> What is this linker? How does it work?

What is google?

d> What does #ifndef HEADER_H statement mean? More specifically, what is HEADER_H?

It's an inclusion guard.

Narue 5,707 Bad Cop Team Colleague

@Narue - I think I remember there being some sort of #pragma that you can use do disable certain warnings. This, obviously, isn't a solution but can help clean things up. Any thoughts?

I'm not a fan of it, unless the warnings are completely stupid. One example of a stupid warning is the "deprecated" warnings Microsoft likes to throw for standard C library functions in their quest to hawk their "safe" string library.

Narue 5,707 Bad Cop Team Colleague

Why not use one version for everything?

That's a matter of personal preference. For consistency I can see using the most feature rich version, but let's consider the following familiar program using that convention:

#include <iostream>

int main(int argc, char *argv[])
{
    std::cout<<"Hello, world!\n";
}

On Visual Studio with /W4 (highly recommended) I get this:

1>------ Build started: Project: C++ Scratch, Configuration: Debug Win32 ------
1> main.cpp
1>d:\users\admin\documents\visual studio 2010\projects\c++ scratch\c++ scratch\main.cpp(3): warning C4100: 'argv' : unreferenced formal parameter
1>d:\users\admin\documents\visual studio 2010\projects\c++ scratch\c++ scratch\main.cpp(3): warning C4100: 'argc' : unreferenced formal parameter
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

And on g++ 4.6.0 with -Wextra (also highly recommended):

-------------- Build: Debug in C++ Scratch ---------------

Compiling: main.cpp
D:\Users\Admin\Documents\CodeBlocks Projects\C++ Scratch\main.cpp:3:5: warning: unused parameter 'argc' [-Wunused-parameter]
D:\Users\Admin\Documents\CodeBlocks Projects\C++ Scratch\main.cpp:3:5: warning: unused parameter 'argv' [-Wunused-parameter]
Linking console executable: bin\Debug\C++ Scratch.exe
Output size is 1.07 MB
Process terminated with status 0 (0 minutes, 0 seconds)
0 errors, 2 warnings (0 minutes, 0 seconds)

If you're like me, you don't want to see any warnings at all. You can fix them by omitting the parameter name and simply going with the type. That's certainly a viable solution:

#include <iostream>

int main(int, char*[])
{
    std::cout<<"Hello, world!\n";
}

But at that point you're already doing something different depending on whether command line arguments are used or not, so what was the benefit again? The only thing I can imagine would be …

Narue 5,707 Bad Cop Team Colleague

C++ requires a cast for conversions to and from void*:

SInt8 one_net_memcmp(const void* const vp1 , const void * const vp2, size_t n)
{
    const UInt8 * up1;
    const UInt8 * up2;

    // If invalid, just return zero since there is no error recovery
    if (!vp1 || !vp2) {
        return 0;
    }

    up1 = (const UInt8*)vp1;
    up2 = (const UInt8*)vp2;

    for (; n > 0; ++up1, ++up2, --n) {
        if (*up1 != *up2) {
            return ((*up1 < *up2) ? -1 : 1);
        }
    }
    return 0;
}
Narue 5,707 Bad Cop Team Colleague

I suppose you can argue that it takes a few more bytes of memory than neccessary

I really don't care about that part. It's the whole potential for unused variable warnings (I'm a stickler for clean compilation) and basically lying to the reader of your code ("I'm using command line arugments...NOT!") that I disapprove of.

Narue 5,707 Bad Cop Team Colleague

what about void main()?

Not portable at best, undefined behavior at worst.

Working fine for me...

You'll find that "it works for me" is not synonymous with "it's correct" in C++. There are a lot of broken things that appear to work when you test, but can and do blow up at the worst possible time.

Narue 5,707 Bad Cop Team Colleague
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    using namespace std;

    ifstream in("test.txt");

    if (in) {
        typedef double Value;
        typedef vector<Value> Vec;
        typedef vector<Vec> Mat;

        Mat v;

        for (string line; getline(in, line);) {
            istringstream iss(line);

            v.push_back(Vec());
            copy(istream_iterator<Value>(iss), 
                istream_iterator<Value>(), 
                back_inserter(v.back()));
        }

        for (Mat::const_iterator it = v.begin(); it != v.end(); ++it) {
            copy(it->begin(), it->end(), ostream_iterator<Value>(cout, "\t"));
            cout<<'\n';
        }
    }
}

:D

Narue 5,707 Bad Cop Team Colleague

operator<< is for output streams, operator>> is for input streams.

Narue 5,707 Bad Cop Team Colleague

So, I try to offer some help and you're going out of your way to prove that I'm basically telling a "flat-out lie".

Please point out where AD accused you of lying. Try being e a little less defensive when people are correcting your mistakes, and you'll probably learn a lot.

My point was just that the version with parameters is better in the sense that it can parse command line arguments.

And the version without parameters is better in the sense that you don't get warnings about unused variables when you don't need to parse command line arguments.

I think that saying the two parameter version is "better" than the zero argument version when you want to parse command line arguments is like saying water is better for hydration than sand. So rather than assume you were needlessly stating the obvious, I took your meaning as the two argument version is "better" when not parsing command line arguments.

My question still stands for sergent though, who very clearly said that it's better to "always" use the two argument version.

Narue 5,707 Bad Cop Team Colleague

istringstream is declared in the <sstream> header.

Narue 5,707 Bad Cop Team Colleague

itoa() is deprecated, and is not part of the standard library

The second part is correct, the first part is not. itoa was never part of the standard library, and thus cannot be deprecated. Deprecated means that a feature of the standard is slated for future removal; it's still standard and available, but not recommended for use.

Narue 5,707 Bad Cop Team Colleague

why dynamic argument deduction deducting it as normal integer?

Top level CV qualifiers are stripped during the type deduction. That's actually expected behavior for template function parameters that aren't a pointer or reference.

Narue 5,707 Bad Cop Team Colleague

Wow, how vague. I'm assuming you have a string literal and want to put a double quote inside of it. In that case you escape it with a backslash:

cout<<"I'm a \"quoted\" string\n";

With character literals the escape is not needed:

cout<<"I'm a "<<'"'<<"quoted"<<'"'<<" string\n";
Narue 5,707 Bad Cop Team Colleague

I said that - because the version with parameters can analyse command line arguments.

That's not a reason for why it's ALWAYS better. Why is this question so difficult for you to understand? There are two fully standard versions of main under discussion right now:

int main()
{
    ...
}
int main(int argc, char *argv[])
{
    ...
}

You and sergent say that the latter is always better. I want to know why it's better in the very common case of not needing command line arguments. If it's your opinion, that's fine, but don't try to palm of your opinion as fact.

Narue 5,707 Bad Cop Team Colleague

Read my previous post AGAIN. I only said that the version that accepts parameters is better.

Then you failed to answer the question. Why is the version that accepts parameters always better?

Let's look at your replies:

int main(int argc, char** argv) is better than int main(), because with the former one, your program can analyse the command line parameters passed to it.

When you want to parse command line arguments, it's obvious that main should be defined to allow that. What I want to know is why you think the two parameter version is better when the program doesn't care one whit about analyzing command line arguments. You see, both you and sergent appear to think that it's better in that case as well.

@WaltP: It is better, because that's what is the standard:

This is a worthless reason, the zero parameter version is also standard.

Narue 5,707 Bad Cop Team Colleague

Since it's a random access iterator, you can take the difference of the two to get the distance between them:

i = myvec.end() - it;

However, this requires a random access iterator. If you decide to change the container to a list, for example, the trick no longer works. The standard library supports a distance function in the <iterator> header that will do the right thing regardless of iterator type:

#include <iterator>

...

i = distance(it, myvec.end());

If the iterator type is random access, the difference trick will be used. Otherwise it falls back onto the less efficient looping methods.

mike_2000_17 commented: Learned something new! cool! +11
Jsplinter commented: Well put, thank you. +2
Narue 5,707 Bad Cop Team Colleague

you should always use the int main(int nargs, args[]);, it is better then just int main()

Please explain why it's better.

Narue 5,707 Bad Cop Team Colleague

a> Where are the actual functions?

Linked into the compiler as either static libraries or dynamic libraries.

b> How do I write a header file such that the actual functions are separately stored?

The header file should contain only declarations. You'll provide definitions in a separate .c file that is subsequently compiled and linked with calling code:

/* header.h */
#ifndef HEADER_H
#define HEADER_H

void foo(); /* Declaration only */

#endif
/* header.c */
#include <stdio.h>
#include "header.h"

void foo()
{
    puts("FOO!!!!");
}
/* main.c */
#include "header.h"

int main(void)
{
    foo();

    return 0;
}
$ gcc header.c main.c

c> How are these two files connected?

The #include directive takes the contents of the file and pastes it over itself. The main.c file above would look like this after such a paste:

/* main.c */
/* header.h */
#ifndef HEADER_H
#define HEADER_H

void foo(); /* Declaration only */

#endif

int main(void)
{
    foo();

    return 0;
}

So at link time the header files no longer exist. Provided the declarations are available, your code will compile. Then the linker puts the definitions and calling code together.

d> What is the advantage of this?

You don't have to put everything in one epically huge file.

Q2. How do I include this header file in my code? Just the normal #include<>?

Convention is to use double quotes instead of angle brackets for headers you write.

Narue 5,707 Bad Cop Team Colleague

What's the problem and how can I fix it?

const in C doesn't mean the same thing as const in C++. In C, the object is read-only at the source level, but does not constitute a compile-time constant like it does in C++. Your error is coming from this clause of the C standard:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

So with your original code, a direct fix is to use a define rather than a const object for the string value:

#if 1
//! Set Pin string
#define ONCLI_SET_PIN_CMD_STR "set pin"
#endif
Narue 5,707 Bad Cop Team Colleague

Out of interest, exactly why is this the case?

It's just a historical limitation of templates and template instantiation. Standard C++ introduced the export keyword for supporting separate compilation, but it failed miserably had has been voted off the island for the next revision.

Narue 5,707 Bad Cop Team Colleague

Is it possible for me to define the template function in an implementation source file instead of defining it inside the class?

The short answer is no. The long answer is still no, but it's a longer no, so I'll stick with the short answer. :)

Narue 5,707 Bad Cop Team Colleague

all I found was that it was unsafe :/

"Unsafe" is often a code word for "I don't understand how to use it correctly". Off the top of my head, I can only think of one function in the standard library that's legitimately unsafe, and it's not strtok. ;)

That doesn't look very C++ish to me, specifically because you're using a C function.

And the C++ version of strtok is...wait for it...strtok. Or manually parsing the string yourself. Or using a third party library that does it for you.

Narue 5,707 Bad Cop Team Colleague

strtok modifies the source string. You have no choice but to make a copy if the original string can't be modified. It also looks like you need to study about arrays a bit.

Narue 5,707 Bad Cop Team Colleague

You're returning on the first iteration, so the result of factorial(5) is essentially 5 * 5 . A correction would initialize i to n - 1 , and only return n after the loop:

int factorial(int n)
{
    for (int i = n - 1; i >= 1; i--)
        n = n * i;

    return n;
}
Narue 5,707 Bad Cop Team Colleague

Pointers to char are assumed to be C-style strings by cout. You can force them to be interpreted as pointers by casting to void*:

cout<< (void*)p <<'\n';
Muhammad Anas commented: Thanks for the help!!!!! +1
Narue 5,707 Bad Cop Team Colleague

abelLazm is a great contributer to this forum!

There isn't a double standard. Anyone who breaks the rules, regardless of contributions thus far, will suffer the same consequences as J. Random Poster on day one. It's not about being mean, it's about being fair.

Narue 5,707 Bad Cop Team Colleague

Look again. Where are you defining check_answer?

Narue 5,707 Bad Cop Team Colleague

Been there, done that. What's your answer?

Narue 5,707 Bad Cop Team Colleague

Why didn't you write a class Matrix???

That's a logical next step, but trying a matrix class without understanding the underlying dynamic memory logistics would be frustrating at best.

Narue 5,707 Bad Cop Team Colleague
Muhammad Anas commented: humm .. it means that I am making progress .. hahaha ... thankyou very much for the feedback!!! +1
Narue 5,707 Bad Cop Team Colleague

The problem is not your code, it's the file. If you can't unambiguously figure out what the codes are without intuition, you can't write code to do it. The file needs some kind of formatting that facilitates separation of codes.

Narue 5,707 Bad Cop Team Colleague

So 256 will be same as 0,257 will be the same as 1,correct?

Assuming char is eight bits, yes.

And how is it in case of signed chars?(is there a rule at all?)

Undefined behavior. Google it.

Narue 5,707 Bad Cop Team Colleague

How will make a difference if it were an unsigned char?

In that case the wrap around is perfectly safe and well defined. Note that vanilla char might be either signed or unsigned.

Is that what you intended to me try?

Yes. Notice the space between the two boundaries? That's what you're printing, and showing the boundaries with > and < allows you to see it.

Narue 5,707 Bad Cop Team Colleague

When char can take integer values from -128 to 127 and both 290 and 20000 are welll out of this range

First, there's no requirement for char to have that particular range. Second, when char is signed, overflow results in undefined behavior. Your code is very dangerous.

In your case, the out of range values are wrapping around until within range, which you can easily see by printing (int)(char)290 and (int)(char)20000 . Since 290 is wrapping to 34 ('"' in ASCII and the low octet of Unicode), I suspect 20000 is wrapping to 32, which corresponds to the ' ' character. So something is being printed, you just don't see it. A better test would show you the boundaries:

cout<<'>'<< (char)20000 <<"<\n";
Narue 5,707 Bad Cop Team Colleague

The underlying problem is failure to include <stdlib.h> and using the abort function without a visible prototype.

vedro-compota commented: ++++++++++ +3
Narue 5,707 Bad Cop Team Colleague

There's nothing you can do in this situation. The file needs some kind of formatting to differentiate between codes, such as a separator or a guaranteed field width. If you can have codes of varying length all mushed up next to each other and no way to determine where the boundaries are, you're SOL.

Narue 5,707 Bad Cop Team Colleague

Fixed. :)

Narue 5,707 Bad Cop Team Colleague

Sorry dude, but I'm very busy right now. If you can't post code that compiles with a cut and paste, I won't help because I lack the time to mock everything up on the off chance that your problem with manifest on my end.