Narue 5,707 Bad Cop Team Colleague

flushall isn't guaranteed to be available as it's a non-standard extension. Besides, you can achieve the same effect as flushall (assuming it does what one might expect) with fflush(NULL).

Narue 5,707 Bad Cop Team Colleague

>no it doesnt ..
Did you use it correctly?

fprintf(stdout,"hello-out");
fflush(stdout);
fprintf(stderr,"hello-err");

stdout is buffered by default while stderr is not. The three ways to flush a buffered stream are filling it up ("hello-out" is unlikely to do that), printing a newline (which you don't), and calling fflush.

Narue 5,707 Bad Cop Team Colleague

>use a loop.
Obviously. Now do it in an elegant way. ;)

Narue 5,707 Bad Cop Team Colleague

>Both describe typedef as making a "synonym" or "another name", for a data type
Yes, that's how I describe them too. But one mustn't confuse "typedef" with "typecast". That's how I interpreted your initial statement, and why I corrected what I perceived to be the problem.

Narue 5,707 Bad Cop Team Colleague

>Well, casting is not the same thing as typecasting.
Erm, yes it is.

>Typecasting just creates an "alias" (another name), your program
>can use, for a certain datatype (typically a struct name).

You're thinking of typedefing. Casting, typecasting, explicit conversion, and type coercion are pretty much the same thing.

>A cast in C is redundant, generally.
When used properly a cast accomplishes one of two goals:

  • Force a conversion where no implicit conversion is allowed. A good example is type punning:
    int x = 12345;
    char *p = (char*)&x;

    &x is a pointer to int, but that type is incompatible with a pointer to char. The cast is required here.

  • Force a conversion where an implicit conversion is allowed to silence warnings. One such example is a truncation warning when there's no chance of truncation:
    char s[BUFSIZ];
    size_t i = 0;
    int ch;
    
    while ((ch = getchar()) != EOF)
        s[i++] = (char)ch;

    getchar returns int only to support EOF. Since EOF is handled separately and won't ever participate in the assignment to char, the possibility that char might be unsigned is irrelevant. As such, on compilers where the int to char conversion throws a warning, the cast says "Yes, I really do know what I'm doing and this conversion is safe"[1].

I know you were talking about casting malloc, but I just wanted to make things clear. In the case of malloc, an implicit conversion of T*<-->void* is allowed, which means the …

Narue 5,707 Bad Cop Team Colleague

>By undefined behavior, do you mean that sometimes it can be changed and sometimes cannot be?
By undefined behavior I mean the C standard makes no guarantees at all about what might happen when your program runs. It's completely unpredictable, even on different runs of the same build. Worse yet, the undefined behavior isn't restricted to that one operation. Once you invoke undefined behavior, your entire program's behavior becomes undefined.

Narue 5,707 Bad Cop Team Colleague

>Can you please elaborate a little more.
It seems like you're making the proper distinction between headers and header files (ie. a header need not be a file). However, aside from that distinction, there's no difference: Include a header and a bunch of stuff gets textually pasted into your translation unit. No magic, just glorified copy/paste.

Narue 5,707 Bad Cop Team Colleague

>Well, unlike C, C++ provides a concept of headers(not header files)
The concept of headers is identical between C and C++.

Narue 5,707 Bad Cop Team Colleague

>is it possible to create my own simple programming language in c++?
Of course it's possible. But it's harder than you probably think.

Narue 5,707 Bad Cop Team Colleague

-1 in an unsigned context is portable, yes.

Narue 5,707 Bad Cop Team Colleague

>I know that by declaring a variable as 'const', its stored in read only memory
Incorrect. There's no rule that says const qualified objects must be stored in read-only memory.

>I found that a const variable's value can be changed using pointers.
Maybe, maybe not. Attempting to modify the value of a const qualified object invokes undefined behavior. There's also no rule that says const qualified objects cannot be stored in read-only memory.

Narue 5,707 Bad Cop Team Colleague

>I think you have bigger issues to address first. My compiler returned 40+ errors.
I got the distinct impression that the code is for illustrative purposes only. It's not his actual code, merely an ad hoc example of the overall design. Simple bugs can be ignored in this case, I believe.

Narue 5,707 Bad Cop Team Colleague

>Because it is an unsigned integer, shouldn't it only be able to store positive values
Yes, that's it exactly.

>Or is the -1 just like a catch all method, so that nothing else can possibly have that value?
If it helps, you can think of -1 in unsigned context as (0U - 1) . The effect is the same: subtracting 1 from 0 underflows and wraps around to the largest value for unsigned int.

Narue 5,707 Bad Cop Team Colleague

>If I have to have an abstract base class with all functions from every derived
>Node class, why don't I just have one Node class with heaps of functions in?

Indeed. Polymorphism is meant to share a common interface with varying behavior. Your problem is trying to use polymorphism with a varying interface. Most likely your design is weak for what you're trying to accomplish. Can you describe the program requirements that brought you to this design?

Narue 5,707 Bad Cop Team Colleague

>it writes the content two times into the file.
Close. It writes the content once, but because of a common bug you read it twice.

>while(!file.eof())
This is the bug. eof only returns true after you've tried and failed to read from the file. Using it as a loop condition without any other tests in the body is a fencepost error.

Here are two common solutions. If your reading function returns a stream state, you can use it directly as the condition:

while (file.read(pass, sizeof pass))
    cout<< pass;

Or you can double up the eof test and avoid processing after a failed read:

while (!file.eof()) {
    file.read(pass, sizeof pass);

    if (!file.eof())
        cout<< pass;
}

Obviously the former is preferred because it's shorter, cleaner, and generally perceived as easier to follow.

Narue 5,707 Bad Cop Team Colleague

When you overflow or underflow an unsigned type, wrap-around occurs. Due to unsigned wrap-around, -1 becomes the largest unsigned value for the type. One common trick is taking advantage of that effect for decrementing loops on an unsigned counter without having to know the actual range of the type:

for (std::size_t i = n; i < (size_t)-1; i--) {
    // ...
}
Narue 5,707 Bad Cop Team Colleague

You forgot to include <string>.

Narue 5,707 Bad Cop Team Colleague

Bumping your thread multiple times isn't likely to encourage help.

Narue 5,707 Bad Cop Team Colleague

>i have made the prog
Then you shouldn't have any trouble proving it.

Narue 5,707 Bad Cop Team Colleague

>So I guess my question would be, why is the for preferred to the while version of creating an infinite loop?
I do it because I like a clean compile, and while(1) produces a constant loop expression warning on at least one of my regular compilers.

>Any hints as to how I could solve this?
Using the character functions from <ctype.h> would be a good start. If there aren't any functions that do what you want, add your own so that there's only one thing to change when porting rather than many.

Narue 5,707 Bad Cop Team Colleague

I'd probably use a database, because tables like this usually end up needing far more robust querying than I'd want to write ad hoc. But I don't see a problem with a vector of objects where each object represents the match up if all you're doing is updating, sorting, and displaying the table.

Narue 5,707 Bad Cop Team Colleague

mw_get_command is recursive. I don't recommend recursive functions that are linear in nature or potentially infinite. Yours is both. A loop would be just as easy to implement:

void mw_get_command(char *cmd) {
    for (;;) {
        int ch;

        printf("Enter a command: ");
        fflush(stdout);

        /* Trim leading whitespace */
        while ((ch = getchar()) != EOF && isspace(ch))
            ;

        if (ch == 'c' || ch == 'n' || ch == 's' || ch == 't' || ch == 'q') {
            *cmd = ch;
            break;
        }
        else
            fputs("Invalid command. Type c<Enter> for help.\n", stderr);

        /* "Flush" the stream */
        while ((ch = getchar()) != '\n' && ch != EOF)
            ;
    }
}

>while(p < alphabet + 26) *(p++) = 0;
Magic numbers are to be avoided.

>srand((unsigned) time(NULL));
>cur_word = rand() % NUM_WORDS;

It's generally recommended that you seed the random number generator only once, not every time rand is called. A quick fix is the first time pattern:

void mw_generate_word(void) {
    static int first_time = 1;

    if (first_time) {
        /* Set up the random numbers generator */
        srand((unsigned) time(NULL));
        first_time = 0;
    }

    cur_word = rand() % NUM_WORDS;
}

This works because the static local variable is only initialized to 1 on the first call. On subsequent calls, it retains the value last assigned. However, note that this trick makes a function non-reentrant.

>for(i = 0; i < strlen(dictionary[cur_word]); i++)
strlen should not be called in the condition of a loop because it often (as …

Narue 5,707 Bad Cop Team Colleague

When you use the <c*> headers as opposed to the <*.h> headers, don't forget that everything is now in the std namespace:

int x = 300;
char out[4];
std::memcpy(out, &x, sizeof(int));

And memcpy is declared in <cstring>, not <cstdio>.

Narue 5,707 Bad Cop Team Colleague

>cannot convert parameter 1 from 'std::string' to 'System::String ^'
You're mixing standard C++ strings with C++/CLI strings. There's a fundamental difference in that C++/CLI strings are Unicode based while std::string is char based. The least frustrating solution would be to pick one and stick with it, but you can also convert between the two:

this->InputLabel->Text = gcnew System::String(TotalInput.c_str());
Narue 5,707 Bad Cop Team Colleague

Well, the error tells you what line the error manifests on, so your first step would be to run your program in a debugger (or use debug printfs if you want to go old school) and verify the state of the variables. Most likely one of your indices is incorrect and steps out of bounds.

Narue 5,707 Bad Cop Team Colleague

Read up on operators and how = is a completely different beast from ==.

Narue 5,707 Bad Cop Team Colleague

>Positive values seem to follow ASCII, but ASCII is only 128 characters. So where are the others from?
It really depends on the character set your system is using, but probably Unicode or some form of extended ASCII.

Narue 5,707 Bad Cop Team Colleague

>Is it really situation dependent and the compiler decides?
Yes.

>printf("%p %p\n", &ival, &ref);
This is a silly test to see if references occupy memory. Obviously due to the semantics of references, you're taking the address of the referent rather than the reference. I believe you'll find that Visual Studio uses a pointer internally if you include assembler output in your build.

Narue 5,707 Bad Cop Team Colleague

You're not reassigning the reference, you're overwriting the value of ival, to which ref is a synonym:

#include <iostream>

int main()
{
    int ival = 12, ival2 = 14;
    int &ref = ival;

    ref = ival2;

    std::cout<< ref <<'\n'<< ival <<'\n';
}

>1 more thing- do references occupy seperate spaces in memory like pointers ?
In general, it's safe to assume that references do take up space under the hood, because otherwise how would the compiler maintain the relationship of reference->referent? Officially, it's unspecified by the language definition, which gives compilers leeway to optimize away references in certain cases. Your program, for example, could potentially be optimized as such:

#include <iostream>

int main()
{
    int ival = 12, ival2 = 14;
    //int &ref = ival;

    ival = ival2;

    std::cout<< ival <<'\n'<< ival <<'\n';
}
Narue 5,707 Bad Cop Team Colleague

>What do you mean by "all with no-op bodies"
An empty body, such that when the member function is called, it returns immediately with some suitable default:

virtual ResultSet getResults() { return ResultSet(); }
Narue 5,707 Bad Cop Team Colleague

>I want its kids to be concrete classes But I don't want to implement the all methods of the class.
Oddly enough we just had a discussion about this. You can make the "optional" member functions simply virtual instead of pure virtual (all with no-op bodies). Then include a pure virtual destructor in the base class to make it abstract if there are no more pure virtuals left in the base class.

It's not a perfect solution, but depending on your actual needs as opposed to the description you've given, it may be suitable.

Narue 5,707 Bad Cop Team Colleague

>This causes an exception, please explain the error.
Simple, an uninitialized pointer is not a pointer to infinite memory. It's an invalid pointer.

Narue 5,707 Bad Cop Team Colleague

>How many years will it take one on avg to master C++ (doing self study) or atleast get a fair touch of this lang?
Mastery is quite different from competence (which is how I interpret "a fair touch"). If you're an experienced programmer you can become competent with C++ in less than a year. Proficiency suggests experience, and experience only comes from writing lots of code, reading lots of code, and studying the literature. So to become truly proficient in C++ I'd say 5+ years unless you have no life. ;)

As for mastery, I'd say it's impossible. C++ is an extremely robust language with not a few nuances, and it's constantly evolving both in the language proper and ways of using it. I think of mastery as knowing and having experience with everything there is to know.

Fbody commented: Agreed :) +2
Narue 5,707 Bad Cop Team Colleague

Dude, just call getchar three times. It's not rocket science:

printf("\nTo calculate a^b, enter value a now.\n");
int a = getchar() - '0';
getchar(); /* Throw away the newline */
printf("\nEnter b now.\n");
int b = getchar() - '0';
printf("a = %d, b = %d\n\n", a, b);

To be truly robust you need to do more, but I fear I'll confuse you too much by explaining all of the nuances of stream I/O.

Narue 5,707 Bad Cop Team Colleague

When you run the program, watch your hands carefully and count how many keys you hit. I suspect you're assuming that the Enter key is somehow treated differently when in reality it too is extracted by getchar as the '\n' character. -38 is fully expected when '\n' is 10 and '0' is 48 (as it is in ASCII).

Narue 5,707 Bad Cop Team Colleague

>do you have any more easy to understand examples ?
Sorry, it doesn't get any easier than that. Now you need to do some work. Come up with hypotheses about how things work and verify that your assumptions are correct with empirical test programs. For example:

#include <stdio.h>

void test(int condition)
{
    if (condition)
        printf("condition (%d): if (condition)\n", condition);
    if (condition != 0)
        printf("condition (%d): if (condition != 0)\n", condition);
    if (!condition)
        printf("condition (%d): if (!condition)\n", condition);
    if (condition == 0)
        printf("condition (%d): if (condition == 0)\n", condition);
}

int main(void)
{
    test(0);
    test(1);
    return 0;
}
Narue 5,707 Bad Cop Team Colleague

>Can anyone help me?
Post your code, or a suitable facsimile of your code that exhibits the problem.

>Is it a problem with the compiler or my program. The latter is not possible
>since I tried out a similar program from a book and got similar results.

It's not possible that you wrote bad code? It has to be a problem with the compiler? Keep in mind that Turbo C was a mature environment in its day, and a bug in simple loop execution isn't exactly one of those deep dark corners where I'd expect new bugs to be found by beginners in a popular and well tested compiler.

Oh, I see you edited your post with some code. The problem is that the second scanf is reading a newline character left over from the previous call to scanf. 'y' != '\n', so the loop terminates. This is a classic problem with stream input in C. Search the forum for flushing stdin and you'll find plenty of discussions on the topic.

Narue 5,707 Bad Cop Team Colleague

>so how does it loop ?
Not false is true, not true is false. That's how boolean logic works. Perhaps if you study equivalent constructs, things will become more clear. The following two snippets do exactly the same thing:

while (!correct) { ... }
while (correct == 0) { ... }

If correct is 0, the loop will continue. If correct is not 0, the loop stops. Likewise, the following two snippets also do the same thing (the opposite of above):

while (correct) { ... }
while (correct != 0) { ... }
Narue 5,707 Bad Cop Team Colleague

Holy excessive comments Batman! Just FYI, if you find yourself commenting nearly every line of code with multiple lines of comments, either your code is far too opaque and needs some serious attention toward readability, or you're including too many unnecessary comments. In reality well written code needs fewer comments than you'd think. My own production code tends to be rather sparse, comment-wise, with no loss of clarity. I honestly almost laughed when I saw a six line comment for every header you included. That's almost as good as the traditional "bad" comment:

i = i + 1; /* Increment i */

I'm on vacation at the moment with only access to an iPad. Making posts is especially tedious, otherwise I would make detailed comments on your code. If you remind me in about a week, I can do a full review for you.

Narue 5,707 Bad Cop Team Colleague

Is there a good alternative to the fflush(stdin)?

Yes, several. I've already posted a sticky on this forum concerning flushing input streams, and the web is full of other resources, so I'm not inclined to repeat what's already been said.

i could use normal gets

No, you should forget gets even exists. This is C++ anyway, and you'd be better served by std::getline and std::string. Then buffer overflow safety becomes a moot point.

As for the single months array would you suggest something like C_Day[366] and have all days in one array like that?

I was thinking more along the lines of C_Day array[12][31] , but it's just a suggestion. Take it with a grain of salt, but take care not to rub that salt in your wounds when you find yourself writing twelve sequential loops instead of two nested loops every time you want to do something with all of the months in a year.

Finally for virtual destructors i was sticking to the coding style in my c++ book in which the author suggests its good practise to make destructors virtual so when the event comes where polymorphism is used its already handled.

That's stupid. It's very simple:

Are you planning to use those classes as polymorphic bases?
(Y) - Okay, make the destructor virtual. Also, best practice is to also make the base an abstract class.
(B) - Okay, don't bother. Why add something that's not immediately useful or likely to be useful …

Narue 5,707 Bad Cop Team Colleague

You should really reconsider relying on non-portable behavior (eg. fflush(stdin)) and non-portable functions (eg. gets_s) if you can avoid it. I'd also recommend merging your months into an array. Even if you waste a few elements of an array, it's still a win in complexity if you consider nothing more than the tedious C_Year::InitYear. Beyond that I'd just be nitpicking.

One thing I did wonder about while reading your code: why virtual destructors? You have no other virtual member functions, and unless you know for a fact that the types will be treated polymorphically down the road, why add the complexity?

Narue 5,707 Bad Cop Team Colleague

strlen is declared in <string.h>, or <cstring> if you want your stuff in the std namespace.

Narue 5,707 Bad Cop Team Colleague

Prime_Finder findprimes();

You've independently discovered a rather subtle problem with C++'s grammar. This line is actually interpreted as a function declaration. The function is called findprimes, has no parameters, and returns and object of type Prime_Finder.

To define an object with the default constructor, omit the empty parens:

Prime_Finder findprimes;
Narue 5,707 Bad Cop Team Colleague

stringstreams are a much cleaner solution than dirty C sprintf functions

Really? The only "dirty" thing I can think of (tedious would be my choice of words) is no std::string support in sprintf. So you need to figure out the maximum size of the file name buffer beforehand. Aside from that, sprintf doesn't seem any dirtier than stringstream for this particular use.

Narue 5,707 Bad Cop Team Colleague

It's an order of operations problem. Inside the loop, you're always testing the next pointer in temp, which is always uninitialized. Take some time to test out how for loops manage the counter variable, because a lot of code relies on that behavior and it's easy to write code that makes false assumptions like this one.

Here's an improved version:

int main(void)
{
    char in[100], *temp[10];
    int i, n = 0;

    printf("Enter the expression: ");
    fflush(stdout);
    
    if (fgets(in, sizeof in, stdin) != NULL)
    {
        temp[0] = strtok(in, " ");

        if (temp[0] != NULL)
        {
            for (n = 1; n < 10 && (temp[n] = strtok(NULL," ")) != NULL; n++)
                ;
        }

        for (i = 0; i < n; i++)
        {
            printf("%s\n", temp[i]);
        }
    }

    return 0;
}

Note the call to fgets (a vast improvement over the unsafe gets) and the fact that input is being tested for success or failure. Next is the loop. Instead of calling subsequent strtoks in the body, it's done in the condition where the condition can be checked before n is updated.

I used n in the first loop to indicate how many strings there are. You could also use NULL as long as temp is initialized to all NULLs first. The second loop uses n as the end case.

Another very important thing to notice is how the first loop also takes care not to exceed the size of temp if there are more than ten tokens. Noticing and …

Narue 5,707 Bad Cop Team Colleague

Thanks for the answers, but maybe my question wasn't clear.
I'm asking specifically regarding bit fields in struct.

Your question was perfectly clear, and my answer is equally clear. Your bit fields can use _Bool and int (signed or unsigned) as the base type without any portability risk. Anything else is not portable.

Narue 5,707 Bad Cop Team Colleague

Arrays don't grow or shrink. If you need dynamic sizing, use an std::vector instead. In fact, you should prefer std::vector in favor of arrays anyway, because they're easier to work with.

[edit: Bah! This is the C forum. Ignore this post]

Narue 5,707 Bad Cop Team Colleague

Clearly Visual C++ 2010 is smarter in terms of implicit standard headers. You failed to include <string>, and the compiler rightly complains. The others don't complain because <string> is probably included inside one of the other three standard headers you've included, so the bug goes unnoticed.

Narue 5,707 Bad Cop Team Colleague

I mean anything else is non-portable. The compiler is free to allow or disallow types beyond int (signed or unsigned) and _Bool, but it must document which types are allowed beyond the ones required by the standard.

Narue 5,707 Bad Cop Team Colleague

Is using other then int types is part of the ANSI C?

The behavior is implementation-defined if you use anything other than _Bool, signed int, or unsigned int.