deceptikon 1,790 Code Sniper Team Colleague Featured Poster

what exaclty u meant by compile time constant ?

A compile time constant in C is essentially a literal value. 123, 5.6, and "test" are all compile time constants when placed in code, but any variable (even a const qualified variable) is not.

secondly, again i want to ask will you explain further when memory is allocated for variables ?

The times differ depending on where the variable is declared and how memory is being allocated. You can typically divide things into three different times:

  1. Static data resides in the executable and is allocated when the process is loaded into memory.

  2. Local variables are stored on the stack. The stack itself is allocated in toto when the process is loaded, but individual variables are doled out from the stack as they're reached during execution. There are details where some compilers differ, as Ancient Dragon mentioned, but you really don't need to concern yourself with that just yet.

  3. Dynamic data, such as that returned by malloc(), will be allocated on request.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

no iam asking about sorting now

Maybe you should finish learning something before running off to learn something new, because you keep making the same mistakes.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

this means when i used memcpy the whole string is copied in str1 while using strcpy str1 contains only "mem"??

Yes, though since you told memcpy() to copy 10 bytes, you wrote too many characters and invoked undefined behavior. str only contains 8 characters, after all (including null characters).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

strcpy() and memcpy() aren't the ones doing the outputing. Obviously if there's a null character in the middle of the string, puts() will stop on it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

strcpy() uses '\0' as the stopping character while memcpy() requires you to specify how many bytes are being copied. memcpy() isn't guaranteed to be safe if the source and destination blocks overlap while memmove() does have that guarantee at the cost of performance.

Due to the types involved, the mem* functions are also more generic than the str* functions.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

can anyone tell me whether we can use const variables for case ...

No, case labels must be a compile time constant. In C the const keyword doesn't make the variable truly constant, it just makes it read-only under normal circumstances. Turbo C might offer a extention to support non-constant labels, but you can't rely on that outside of Turbo C.

likewise if we use this const variable as array index during initialisation...would it work...

No. This works in C++ because C++ changed the semantics of const, but not C.

can anyone explain ...at what time memory is allocated for variables...

It depends on where you declare the variable, but for the most part variables are stored on the stack at runtime.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

My question is when does this function works improperly and why?

Technically it works improperly when you call it with an input stream or an update stream in input mode. That is, if you use fopen() with a "w" mode, or a "+" mode and you're currently in the process of reading from the stream, or stdin.

In practice, all of the above situations are okie dokie iff the compiler supports them (and some do, including Borland and Microsoft compilers). In terms of best practice, fflush() on an input stream is frowned upon.

However, note that calling fflush() on an output stream is both well defined and recommended for things such as forcing a user prompt to display, well...promptly. :)

Nowadays I use scanf("[^\n]") to flush input stream. Is this ok?

Close. The correct call for scanf() to read up to a newline would be:

scanf("%*[^\n]");

This isn't complete though, because the newline will still be in the stream. You still need to extract it. One way would be to add an ignored character match in the format string:

scanf("%*[^\n]%*c");

This might not be as flexible though, if you want to do other stuff like count discarded characters. Another way would be to call getchar() after scanf():

scanf("%*[^\n]");
getchar();

Finally, there's the far more common (and faster!) method of calling getchar() in a loop. I'll even give you a function that you can call instead of having to write it …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

also did the program compiled without including the ctype and string libraries necessary for using tolower and strlen functions

It's not good practice, but that's allowed except when the function being called uses variable parameters (like printf() or scanf()). If you're calling a variable parameter function then a declaration must be in scope or you invoke undefined behavior.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Can you tell me the exact difference between statement and expression ?

The C99 standard defines an expression as "a sequence of operators and operands that specifies computation of a value, or that designates an object or a function, or that generates side effects, or that performs a combination thereof".

A statement is defined as "specifies an action to be performed". That's obviously not very helpful because it seems the same as an expression just described with fewer words, but the standard goes on to explain about an expression statement which has grammar like so:

expression-statement:
    expression(optional) ;

So an expression statement is an optionally empty expression followed by a semicolon. The case of an empty expression followed by a semicolon is called a null statement. And the point of the expression statement is a statement used solely for its side effect (ie. the effect of the expression). This distinction is made because there are other statement types that do their own work, such as conditional statements and looping statements, or that collect statements as in the compound statement (also known as a block).

If you're feeling especially daring, you can read the standard here. But be warned, you're not expected to find much of it useful at this point in your education, it's written to be ultra precise for people who are writing compilers.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

error is at line 23 can i use ascii value of vowels????

Two things:

  1. POST THE ERROR! You should make it as easy as possible to help you, and forcing us to either be a human compiler or copypasta your code into a compiler to see what the hell you're talking about is encouraging people to not help.

  2. Read your own errors. If you had taken the time to read the error and study your own code, you wouldn't have needed to ask for help. This is a very obvious error and a very common bug among beginners and experienced C programmers alike. You're using = instead of == for comparison.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is the reason that expression changed into statement , that one is the reason for this ?

Yes, that's the reason.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

what is problem with these expressions ?

They're syntax errors. Wrapping a statement in parentheses makes it an expression, and a statement isn't allowed inside an expression. You can simplify the error like so:

int main(void)
{
    int x;

    /* Adding a semicolon after 10 makes it a statement */
    (x = 10;);

    return 0;
}

So what you have is a statement x = 10; inside an expression (x = 10;) which itself is a statement (x = 10;);, and this is illegal. That's just the way the syntax of C works. If the inner semicolon weren't there, ie. (x = 10);, this example would work just fine because now you're wrapping parens around an expression, which is perfectly legal.

However, if you have declarations then you have absolutely no choice but to terminate the declaration with a semicolon, which makes it a statement, which means you can't nest it inside an expression.

in my answer book, it is written "t can't be dclared in parentheses".

That's true, though it's not the entirety of the problem because even if you move the declaration outside of the parens you'd still have an error due to there being statements inside the parens. However, in that case you can fix it with the comma operator:

int t; (t = a, a = b, b = t);

This will work, but I don't recommend it for your macro because there are still problems that I've …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm more than happy to explain anything about my posts, so please don't be afraid to ask for clarification. If you stay quiet, I'll just assume that you understood and expect you to apply that understanding in future posts.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is it possible to write our own display statement and input statement

Certainly. How do you think the stuff from stdio.h was written? One cool thing about the standard C library is pretty much all of it can be written directly in C. I've actually implemented the standard C library before, and whole books have been written with that focus.

As far as writing your own output function without utilizing the standard library, you'll almost certainly end up using a system library like Linux's write() or Windows' WriteFile(). Sure, you could use assembly interrupts, but that's just crazy talk unless you're writing for a platform that for some reason doesn't expose a C interface for I/O.

On a side note, the linked book is one of my favorites. The code is a hard read, but you can learn a lot from it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Try opening windows.h and reading the declarations. Then for each declaration, do a search on MSDN.

And here's a tip: MSDN's search facility is an embarrassment of epic proportions, so if you need to do anything but an exact match search, use Google with the site: filter.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So my question is why virtual functions are needed if same task can be achieved by scope resolution operator?

I'll answer your question with another question: If you're given nothing but a pointer to the base, how do you know which type to use for the scope resolution operator?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's not as simple as that, but if you're only using getline() then there should be no need to ignore garbage if you're using getline() correctly. The problem of garbage nearly always stems from reading partial lines or mixing getline with formatted input (in the form of the >> operator).

The latter is explained in painful detail here.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So I request you "DON'T GUESS FROM THE COMPILER THAT WHICH NATIONALITY A PERSON HAS".

It looks to me like he guessed India from the OP's name, and then further speculated the compiler based on previous observations (an observation I've made as well). I don't think you should feel insulted, but I'll ask two questions that may calm your anger:

  1. Is Shankar an uncommon name in India or exceptionally common in another country that you would be insulted if it were associated with India?

  2. Is Turbo C not the most commonly used compiler in educational institutions by far in India?

If you answered yes to either of those then you can take offense and address the issue privately with DeanMSands3. Otherwise, I'd suggest growing some thicker skin and not taking offense at the first potentially negative mention of your country. That's how pointless wars are started.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

the compiler say the error is at here at 18th line if(ch== '')

There's no such thing as an empty character literal, the compiler is telling you that. I can only speculate about what you were trying to do, which is check for the end of a string? In that case you test for '\0'.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What happen when i remove parenthesis?

Allow me to make the problem more obvious:

if (int temp = x; x = y; y = temp;)

Wrapping parentheses results in taking those three statements and wrapping them in an expression, much like putting them in the condition expression of an if statement, which is syntactically illegal in this case.

And what is meant by "have to be contend with requirement that declarations be the begining of a block" ?

This is legal C99, but illegal C89:

#include <stdio.h>

int main(void)
{
    puts("Starting main...\n");

    int i; /* Declaration after a statement in the block */

    for (i = 0; i < 10; ++i)
        printf("%d\n", i);

    return 0;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I suspect it would be knowledge of Microsoft software like Visual Studio or the Office suite. By the way, that question is unrelated to this thread, and C in general. You would be better off starting a new thread in an appropriate forum.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So, the correct way to do is

No, remove the parentheses entirely. But that's still problematic because now you'll have to contend with the requirement that declarations be at the beginning of a block (unless you're compiling as C99 or later).

And what exacltly do you want to tell after giving the do..while example? I understand what u said. But, What exaclty you want to tell me ?

I want to tell you the right way to accomplish what you're trying to do.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why cant we ? please explain me this ?

Copy and paste the text yourself to see:

/* SWAP(x, y, int); */
(int t; t=x, x=y, y=t);

Yea, that looks like it'll compile...not. Why? Because there's a mismatch between the parentheses and the semicolons. You want the last part to be a smiley, not an upside down frowny:

(int t; t=x, x=y, y=t;)

Here's a trick for when you want to end a function macro instantiation with a semicolon:

#include<stdio.h>

#define SWAP(a, b, type) do { \
    type t = a;               \
    a = b;                    \
    b = t;                    \
} while (0)

int main(void)
{
    int x = 10, y = 20;

    SWAP(x, y, int);
    printf("%d %d\n", x, y);

    return 0;
}

The magic is in the do..while(0). You probably already know that do..while ends with a semicolon, and by setting the condition to 0 you ensure that the body runs only one time. The end result is that instead of the awkward looking instantiation that looks like a syntax error:

SWAP(x, y, int)
printf("%d %d\n", x, y);

You have the more conventional semicolon terminated function "call":

SWAP(x, y, int);
printf("%d %d\n", x, y);

Also, the braces of the do..while ensure that you have a nested block, and the declaration of variables local to that block don't step on variables of the same name in the calling block (which isn't a problem here, but can happen for …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's unspecified behavior if you access a member of a union that's different from the last one used to store a value. Though one of three cases can be expected:

  1. The correct value will be printed.
  2. A garbage value will be printed.
  3. The program will blow up from a trap representation.

In the case of #1, the bytes stored in the union's memory are a valid and consistent representation of the type of the member being accessed. So in the code you posted, I would expect output of 20.

In the case of #2, there's no meaningful representation of the bytes, so you'll get a garbage value. This would be the case for storing an integer value and then trying to access it through a floating-point member:

#include <stdio.h>

int main(void)
{
    union foo { int a; double b; } foo;

    foo.a = 123;
    printf("%f\n", foo.b);

    return 0;
}

Finally, if the value when represented by the type of the accessed member is a trap representation for that type, you're screwed.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What compiler are you using?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you don't bother to read my replies then I'm going to stop trying to help you. How do I know you aren't reading my replies? Because if you were, then you'd realise that I already answered this one with another post on a similar topic.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's not quite the same.

Meaning what, exactly? Are you doing a conversion but not sure your conversion is accurate? Are you getting errors when running it? Unexpected behavior? What's not right that you want fixed?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The program still runs without errors. Did I do that right?

Nope, you forgot to read the warnings. Just because the code compiles and runs doesn't mean it compiled cleanly and is correct.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Are you sure you're not a bad programmer? Because your logic is atrocious. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

No, but this is the case for bit field having width zero.

A zero width unnamed bitfield aligns the next bitfield to the listed type boundary rather than a programmer-specified number of bits. A non-zero width unnamed bitfield aligns the next bitfield to a programmer-specified number of bits:

/* Assuming unsigned int is 32-bits */
struct Foo {
    unsigned a: 5;
    unsigned b: 2; /* Take up 7 bits starting at the 1st bit */
    /*
        Force the next bitfield to start at the next 32-bit entity.
        This means we're skipping the remaining 25 bits of the current
        32-bit entity.
    */
    unsigned  : 0;
    unsigned c: 7; /* Take up 7 bits starting at the 1st bit */
};

/* Assuming unsigned int is 32-bits */
struct Foo {
    unsigned a: 5;
    unsigned b: 2; /* Take up 7 bits starting at the 1st bit */
    /*
        Skip the next 7 bits of the current 32-bit entity.
    */
    unsigned  : 7;
    unsigned c: 7; /* Take up 7 bits starting at the 15th bit*/
};
I_m_rude commented: ohh! really awesome! +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your corrections are irrelevant because the problem is the same as in my speculation about how the code really looked. b and c aren't parameters to the macro, they're expected to be declared and initialized as named variables:

#include <stdio.h>

#define loop() for (; b < c; b++)

int main(void)
{
    int i = 0;
    int b = 0, c = 15;

    loop(i, 15)
    {
        printf("%d\n", i);
    }

    return 0;
}

The argument list is actually wrong, and you should at least get a warning about having too many arguments in a parameter list expecting none. As you already know, the correction is to add those parameters to the macro:

#include <stdio.h>

#define loop(b, c) for (; b < c; b++)

int main(void)
{
    int i = 0;

    loop(i, 15)
    {
        printf("%d\n", i);
    }

    return 0;
}

What you can't do is remove the empty parameter list, like this:

#define loop for (; b < c; b++)

The reason is because when you say loop(i, 15), what actually happens is for (; b < c; b++)(i, 15), and that's a syntax error unless the next token is a semicolon to turn (i, 15) into a do nothing statement.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So, how to access those bit fields and what is it's use.

You don't access them, that's the point. They're used for padding and alignment purposes.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Any other link can you provide for making my concepts more and mpre clear.

This one is mostly about data structures and algorithms, but there's also a reasonably good article on pointers which includes mention of how they relate to arrays.

I don't doubt I could come up with more links, but my memory works more along the lines of hearing a specific question or comment and thinking "oh, I read an article about that" as opposed to just randomly thinking of something cool or useful.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

b=0 isn't the only difference, you also added the for keyword and an argument list to the macro which assigns i to b and 15 to c instead of expecting b and c to already exist as variables. It's actually a miracle that the original code compiles at all (I suspect it really doesn't though, and you're just paraphrasing).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think all of your problems stem from re-opening the file in your functions. Opening a file stream in write mode will truncate the file to zero length, so every time you call print(), the data in the file gets wiped out.

One way to fix it without significant changes is open the file in main() just before your second loop, remove the call to open() in print(), and finally remove the call to close() in display():

#include <iostream>
#include <cstdlib> 
#include <fstream>
#include <vector>
using namespace std;

int array[7][4];

fstream file2;

template< typename T > void display( const vector< vector<T> >& matrix )
{
    for(int i = 0; i < 7; ++i)
    {
        for(int j = 0; j < 4; ++j)
        {
            array[i][j] = matrix[i][j];
            file2 << array[i][j] << " ";
        }
        file2 << "\n";
    }    
    file2 << "\n";
}

template< typename T >
vector< vector<T> > get( const vector< vector<T> >& m, size_t n, size_t i, size_t j )
{
    const size_t N = m.size() ;
    vector< vector<T> > slice(n) ;

    for( size_t k = 0 ; k < n ; ++k )
        for( size_t l = 0 ; l < n ; ++l )
            slice[k].push_back( m.at(k+i).at(l+j) ) ;

    return slice ;
}

template< typename T > void print( const vector< vector<T> >& m )
{
    for( size_t i = 0 ; i < m.size() ; ++i )
    {
        for( size_t j = 0 ; j < m[i].size() ; ++j )
        {
            file2 << m[i][j] << " …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The algorithm is correct, though two things stand out:

  1. You don't account for a number that's less than 1. In real code this can cause problems.

  2. The loop stops when counter is equal to 1, but due to the way the factorial and counter interact, you could stop the loop at 2 and still get a correct result. For this program it's not a big deal, but in complex loops you can benefit from not doing unnecessary work.

There's also the matter of factorial growth and potentially overflowing the number data type, but that's not really a concern for pseudocode. However, it couldn't hurt to recognize that when translated to real code, you have to deal with the limitations of the computer.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This may help. It's written by Chris Torek, who's a man deserving of great respect due to his deep knowledge of C.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I don't particularly like how you're trying to lump everything together because it complicates an already complicated algorithm. There are three separate parts to replacing a substring:

  1. Find a matching substring.
  2. Make room for the replacement.
  3. Insert the replacement.

Separating the tasks conceptually will help you write code that can easily be modularized into functions. Also note that making room for the replacement isn't as simple as it first seems because you need to consider differing sizes of the matched and replacement substring:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char line[BUFSIZ] = "thisisatest";
    char match[BUFSIZ] = "isa";
    char replace[BUFSIZ] = "BOOGA";
    int i, j, k;

    /* Step 1: Find a matching substring (without the standard library) */
    for (i = 0; line[i]; ++i) {
        for (j = i, k = 0; line[j] && match[k]; ++j, ++k) {
            if (line[j] != match[k])
                break;
        }

        if (match[k] == '\0')
            break;
    }

    /* Step 2: Make room for the replacement (without the standard library) */
    if (line[i]) {
        int old_end = i + strlen(match);
        int new_end = i + strlen(replace);

        if (old_end > new_end) {
            /* Make a smaller hole */
            while ((line[new_end++] = line[old_end++]) != '\0')
                ;
        }
        else if (old_end < new_end) {
            /* Make a bigger hole (don't forget to shift the null character too) */
            int j = strlen(line);
            int k = strlen(line) + (new_end - old_end);
            int n = j - old_end + 1;

            while (n--)
                line[k--] = line[j--];
        }
    }

    /* Step 3: Insert …
I_m_rude commented: great +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I would say that, particularly in portable code, the C bitfield syntax is of no use.

Only if you're using it to map an object or performing I/O with it. Bitfields are especially useful for flags, and in that case they're generally simpler to work with "out of the box" than bit twiddling. You can write macros to simplify the bit twiddling, but that's extra effort that may not be necessary.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You'll probably be able to relate to this

That's hilarious, unfortunately because it's so true. For example, programming books have an annoying tendency to leave the hardest and most important parts as "exercises for the reader".

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For future reference, both a newline and a space in the format string are unnecessary. Any single whitespace character will tell scanf() to read any and all subsequent whitespace from the stream, so technically you could do this:

scanf(" %c", &b);

And it'll catch any number of spaces, tabs, and newlines. It'll also royally jack up your I/O logic if you're not expecting that behavior. ;)

Also note that the only specifiers that don't read leading whitespace by default are %c, %[, and %n. All of the other specifiers do the "right" thing.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm willing to bet that you didn't think the Enter key counts as a character in the stream. Your second scanf() reads the newline from pressing the Enter key, so you're replacing whatever is typed for b with '\n'. Unless you type multiple characters for b, of course.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

scanf()'s %s specifier doesn't read whitespace, that's the delimiter. Since you learned not to use gets(), the proper replacement is fgets(), not scanf().

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For the most part. For everything else there's google.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm not aware of any list like that. Maybe you could compile one as you learn C. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Doesn't compiler give the error if array limits are crossed ?

It's undefined behavior, anything could happen.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

To answer that kind of question, you need to understand the nature of the problem as well as how it manifests. That's a matter of experience.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@deceptikon sir, So that means there isn't any solution for this problem as you said it must roll back fully ?

No offense, being fully aware that leading with "no offense" means something offensive will follow, but I find this back and forth of saying the same damn thing with slightly different words tiresome. I said something very clearly and with no ambiguity (ie. "you really have no choice but to roll back up the recursive chain"). You repeated it equally clearly and with full understanding (ie. "there isn't any solution for this problem as you said it must roll back fully"). Why should I repeat myself when it's obvious that you understood?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There are many libraries you can (and should!) use. Cryptography is exceptionally easy to get wrong, where the result appears to work but is easily cracked. OpenSSL is one popular library.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, I double checked and it's definitely undefined behavior to modify a const-qualified object.