sepp2k 378 Practically a Master Poster

In C++ pre-11 you'll need to cast the first argument to a floating point type in order to tell the compiler which overload to use (there are no overloads taking int as the first argument before C++11). Or in this case you could just replace 10 with 10.0 since it's a constant.

In C++11 your code should work as fine.

sepp2k 378 Practically a Master Poster

You do not use parsing algorithms to generate a list of tokens. The list of tokens is the input to the parsing algorithm. The output of the algorithm is generally an AST or some kind of intermediate representation of the code (or in some cases even the end product of the compilation or interpretation).

To generate the list of tokens you write a so-called lexer, which usesa totally different algorithm. This algorithm is usually based on regular expressions, not CFGs, and works by implementing a state machine that keeps track of which of the possible regular expressions can still match the input read so far.

A lexer can either generated by tools like lex (or its many clones like flex) or written by hand. Since the tokens for most languages follow quite simple rules, hand-writing lexers can often be relatively simple. For example a state machine for many common languages could follow rules like this:

Start-state: If the current character is a letter or underscore, switch to ID-state. If it's a digit, switch to Number-state. If it's a quote, switch to String-state. If it's an operator-start character, switch to operator state. If it's white space, discard it.

ID-state: If the current character is in [0-9a-zA-Z_], add it to the token. Otherwise: token is finished; if the characters read form a keyword, it's a keyword token; otherwise it's an identifier token. Return to Start-state.

Number-state: If the current character is a valid character for a number (possibly taken into account suffix …

Ancient Dragon commented: helpful +14
sepp2k 378 Practically a Master Poster

First of all sp::bool does not exist, you probably meant sp::b there.

But even then it won't work because ADT is about where the type of the argument is defined, not where the variable is defined (the argument doesn't even need to be a variable). The type of the argument here is bool and since bool is not defined in the sp namespace, that namespace won't be part of the lookup.

If you define a type in sp (maybe as a typedef) and then make b an instance of that type, the lookup will behave as you expect. It will even still behave that way if you define b outside of the namespace (as long as the type is defined within the namespace).

sepp2k 378 Practically a Master Poster

Pointers are iterators (random access iterators to be specific) and they are in fact commonly used as such. For example std::vector<T> uses T* in most (possibly all) implementations (except in the case of vector<bool>, which is a special case).

On the other hand there are many iterators that aren't pointers. For example std::list<T>::iterator could not possibly be a pointer type.

sepp2k 378 Practically a Master Poster

Yes, cup1 is an object (or rather it's a variable referring to an object - just like cup2).

The biggest difference between cup1 and cup2 is that, if the Coffee class defines public methods in addition to those declared in CoffeeInterface, you will be able to call those on cup2, but not on cup1.

Another difference is that, if you have a method m that has one overload for Coffee and one for CoffeeInterface, then m(cup1) will call the overload for the interface while m(cup2) will call the overload for the class.

JamesCherrill commented: Good answer +15
sepp2k 378 Practically a Master Poster

Is elements a collection of string pointers or of strings? Judging from the error messages I'd say it's the latter, so your lambda needs to take a string or string reference as its argument.

Since destroy takes a pointer, you'll have to pass a pointer to your string to it. Note that if you make your lambda take a string, it will have its own unique address that's distinct from that of the string in the collection, so you probably want to use a reference.

iamthwee commented: rashakil fol in hiding +14
Vasthor commented: always had this funny syntax going wrong, thnx though +2
sepp2k 378 Practically a Master Poster

So by writing the line "objNumber* num1obj;", you have created a pointer variable in heap

Like all local variables num1obj lives on the stack, not the heap.

sepp2k 378 Practically a Master Poster

num1obj has not been initialized and is thus neither pointing on the stack nor on the heap - it is pointing nowhere at all. Therefore dereferencing it invokes undefined behavior.

Note that this is in no way specific to objects. If you dereferenced an int pointer that you did not initialize, it would cause the same problem.

sepp2k 378 Practically a Master Poster

Yes, VLAs and implicit casts from void are not allowed in C++. You'll have to compile this as C code.

Ancient Dragon commented: yes :) +14
sepp2k 378 Practically a Master Poster

The problem is that it is taking away too much, double the cost

System.out.println("Calc: " + this.curGold + " - " + goldValue + " = " + (this.curGold -= goldValue));
this.curGold -= goldValue;

In the above code you execute this.curGold -= goldValue twice (once in the print statement and once in the line afterwards), so the gold value will indeed be subtracted twice.

and also will not buy if the current gold is equal to the cost.

public boolean hasEnoughGold(float cost)
{
    if(getCurGold() > cost)
        return true;
    return false;
}

Right because getCurGold() > cost is not true if getCurGold() is equal to cost.

PS: if(foo) return true; else return false; can just be written as return foo; - no need for the if.

sepp2k 378 Practically a Master Poster

I believe that H(t1) stands in for a list of all the synonymes of t1

According to the paper it stands for "a set of tuples (h, f), where h is a hypernym and f is the number of times the algorithm has found evidence for it".

So n stands for the number of times the algorithm has found evidence of h being a hypernym of t1 and m stands for the number of times the algorithm has found evidence of h being a hypernym of t2.

In general whenever you're unsure what exactly something means, it's a good idea to go back to where it was defined and read the definition carefully. In this case knowing that H produces a set of tuples - not just a set of hypernyms - was crucial to understanding what n and m are, so it's important to pay attention to those kinds of details.

ddanbe commented: Nice! +15
iamthwee commented: rashakil is this person +14
sepp2k 378 Practically a Master Poster

Let's say you have 25c and can use the 10c and 5c coins. Since 15 is greater than 10, you may use a 10c coin. If you do, you have 15c left (for which you again may or may not use another 10c coin). If you don't, you still have 25c left, which you pay with 5c coins.

So the total number of ways to give change for 25c using 10c and 5c coins is the number of ways you can give change for 25c using only 5c coins (n[0][25]) plus the number of ways you can give change for 15c using 10c and 5c coins (n[1][15]).

sepp2k 378 Practically a Master Poster

When declaring a variable, preceding the variable name with a * makes it a pointer. Preceding it with a & is illegal (in C - in C++ it makes the variable a reference).

In an expression & takes a variable and produces a pointer to that variable, whereas * takes a pointer and produces the value that that pointer points to.

sepp2k 378 Practically a Master Poster

what is meant by static scope and dynamic scope?

The scope affects whether a given variable can be accessed from a given location in the code and, if there are multiple variables with the same name, which one is meant by a given use of the name.

Using static scope you can use variables that are defined globally or inside a code block that you're nested in. This means that, when using nested and/or anonymous functions (in languages that support them), such a function can access variables of the enclosing function even after that function is no longer running. If multiple variables with the same name could be accessed by that logic, the inner-most one is chosen.

Using dynamic scope you can use variables that are defined globally or which exist in any activation record currently on the stack. This means that you can access local variables of another function if (and only if) that function called you. If multiple variables with the same name could be accessed by that logic, the one that has been most recently pushed onto the stack is chosen.

Suppose i have 2 functions (main) and (fact).The activation record for main knows the address of fact so that it can call it.How? Do main and fact functions link before compiling?

(Assuming the functions are defined in different compilation units - otherwise linking is irrelevant) No, linking happens after compilation. The address of fact is simply not known until linking. Before then, …

sepp2k 378 Practically a Master Poster

In your example code you only push one tree into the vector, so that's not enough to reproduce your problem. My guess is that in your real code you have a loop around lines 3 to 10. So at the end of each iteration of the loop, myRBTreeCopy goes out of scope and the pointer you stored in the vector becomes invalid. Then dereferencing that pointer later invokes undefined behavior. Since each instance of the my RBTreeCopy variable presumably reuses the same memory address on your implementation, this undefined behavior manifests itself as all pointers pointing to the same tree.

The easiest way to fix your problem would probably be to store the trees directly in the vector instead of using pointers. If that's not an option, you'll need to use new to allocate the trees on the heap.

PS: An RB tree is not a linked list.

sepp2k 378 Practically a Master Poster

If the user enters a number too large to fit into a long, LONG_MAX will be returned. If the user enters a number that's exactly LONG_MAX, LONG_MAX will also be returned. The first would be an error case, the second would not (in the case that sizeof(int) == sizeof(long) - otherwise LONG_MAX would still be too large to fit into an int and the problem would be caught by the <= INT_MAX check). So we need errno to distinguish between these cases.

deceptikon commented: Good explanation. +13
sepp2k 378 Practically a Master Poster

The only return true is your code is on line 5. That line is inside the each, so it can only be reached if the array is not empty (otherwise the code in the each does not execute at all). If the array is empty it goes directly to line 10 and thus returns false.

If you want to return true for an empty array if the argument is zero, you need to add a check whether the array is empty and the argument zero and return true in that case.

If you also want to return true if the array contains the element n (and thus no adding is necessary), you could just append the element 0 to the array before the each. That way no special case would be necessary and sum_to_n?([],0), sum_to_n?([42],42) and sum_to_n?([23,13,7],13) would all be true (if that is indeed the intention).

sepp2k 378 Practically a Master Poster

{0} and {1} are placeholders for the second and third arguments to WriteLine respectively. So {0} is replaced with the value of n (the second argument) and {1} is replaced with the value of Fib(n) (the third argument). So Console.WriteLine("F({0}) = {1}"**, n, Fib(n)) will print F(3) = 6 when n is 3.

For more information see Composite Formatting (MSDN).

PS: If that wasn't your question, please clarify.

sepp2k 378 Practically a Master Poster
  1. If by "const" you mean macros (as opposed to a variable that has been declared const), it's convention in C and C++ for macro names to be in ALL_CAPS to easily distinguish between macros and functions/variables.

  2. That's a matter of style and really up to you (or your team's style guidelines if you're a part of a larger team).

sepp2k 378 Practically a Master Poster

Okay and what about my other questions? What does line 29 in main.cpp look like? If you replace NewLine with std::endl, does that make a difference?

From the error message it looks like the problem might be because endl is an overloaded function, so the compiler does not know which overload (and thus which type) to pick. This would be unrelated to the fact that you defined a NewLine macro.

To fix this you could define NewLine as a function that explicitly takes an ostream as its argument. Or you could just use cout normally and not bother with any of this, which is really the preferable option if you ask me.

sepp2k 378 Practically a Master Poster

As I said there's only one function parameter, so no commas. If you write soemthing like int arr[42], you don't have a comma in there either.

sepp2k 378 Practically a Master Poster

the template have 2 parameters, but you transform 'N' in second parameter

What do you mean by "transform" here? I take N as the second template parameter.

you don't use comma

There's a comma between typename T and size_t N - where else do you expect a comma?

Just to clarify: There are two template parameters (T and N) and one function parameter (arr, which has type (T&)[N], i.e. "reference to an N-element array of Ts"). The template parameters are separated by commas. The function parameter is not as there's only one.

sepp2k 378 Practically a Master Poster

In a parameter list T arr[] is the same T* arr, so arr is a pointer. The only way to pass an array to a function is by reference. To declare an array reference you'd write T (&arr)[42] where 42 is the size of the array. In this case you'd probably want it to work with any size of array, so you'll need to make the size a template parameter like this:

template <typename T, size_t N>
void print_array(T (&arr)[N]) {
    ...
}

Now you don't even need to use the sizeof trick to get the length of the array, you can just use N.

The downside of this approach is that you'll only be able to use the method with variables of actual array types, so you won't be able to use it with arrays that have been allocated using new (as those would only be accessible through pointers - not directly through a variable). Of course that is true when using the sizeof trick as well.

If you want your function to be able to work with newed arrays too (or generally with arrays that you only have a pointer to), your only option is to take a pointer as your first argument and the size as the second.

sepp2k 378 Practically a Master Poster

You should never prefer macros over inline functions. The only case where you'd use macros would be if you're writing for a compiler that does not support inline functions¹ or you're using macros as something other than a poor man's inline functions² - though even then you should think about whether you couldn't implement the desired functionality in pure C before you decide to use macros.

¹ Standard C did not support inline functions until the 99 standard though some compilers supported them as an extension before then.

² For example gtk/gobject uses macros to implement its object system. QT (though that's C++, not C) uses macros (in combination with its moc preprocessor) to implement its signals and slots. Its foreach loop is also implemented as a macro.

nitin1 commented: from where you guys come to know about all these things, you are filled-up with loads of knowledge. :D +3
sepp2k 378 Practically a Master Poster

I think there's been an important confusion of terminology here, so I just want to clear this up:

The three paragraphs you quote above ALL refer to floating constants, and clearly state that, right at the start of each paragraph.

Yes, because, as I said, what you call "magic numbers" is called a constant. The standard defines a floating constant as a sequence of digits with a dot in between (or an E or whatever). Unless I completely missed your point, that's what you refer to when you use the term "magic number": a sequence of digits. The term "magic number" does not exist in the standard.

handling "magic numbers" as constants

They aren't "handled" as constants, they are what standard defines to be a constant. The terms (integer + floating) "constant", as defined by the standard, and "magic number", as used by you, are 100% equivalent (again: unless I completely misinterpreted what you're trying to say). There's nothing that you would call a magic number that doesn't meet the standard's definition of a constant and there's nothing that would meet the standard's definition of a floating or integer constant that you would not call a constant.

deceptikon commented: Beat me to it. :) +12
sepp2k 378 Practically a Master Poster

It's not quite clear to me, what you're trying to do here. If you want the division to only happen if x = 1 is false, it should be inside the else block of the first if. Also every if needs an else, so your first if causes a syntax error because it doesn't.

Also if x is supposed to be the result of the division, why do you already use it on line 2 when the division hasn't happened yet? Further to define a local variable, you'd use let, just writing x = value is not syntactically valid. If you want to change the value of an already existing int variable named x, you can't do that. Variables in SML are immutable. If you want to simulate mutable variables, you can use an int ref instead. But you probably shouldn't.

It also seems strange that your hello function does not take any arguments. Or that both operands to the division are constant (why not just write x = 2 then?).

Here's something that I think might be close to what you might want:

fun hello x =
    if x = 1 then true
    else
        let
            val y = 10 div x
        in
            if x = 4 then true
            else false
        end;
sepp2k 378 Practically a Master Poster

You are creating a pointer to an array

No, he's not. He's creating an array of arrays of pointers.

and trying to output the size, this is not allowed sice the compiler does not know what the pointer is pointing to.

Yes, it's allowed and yes, the compiler knows perfectly well what p (or rather the pointer that p decays to) is pointing to: to a 20 element arrays of int pointers. So it returns sizeof(int*) * 20

And if he had created a pointer to an array (by writing int (*p)[10][20] instead of int *p[10][20]), it'd still be allowed and the compiler would still know what p points to: a 10x20 array of int. So in that case it would return sizeof(int) * 200.

ddanbe commented: Nice! +14
sepp2k 378 Practically a Master Poster

Can you be more specific about what kinds of problems you're looking for in terms of scope and "topic" (like should they be more about algorithms or application design etc.) and how tough they should be?

If you're interested in algorithmic problems, you can find ones of various difficulties on sites like the Spehere Online Judge or the UVA Online Judge. If you're interested in mathematical problems (with programatic solutions), Project Euler has many nice ones (though most of them are pretty tough and generally require more mathematical than programming knowledge).

sepp2k 378 Practically a Master Poster

It will be whichever the compiler chooses (arbitrarily or not). So, clearly, there is no telling which of the increment operators will be evaluated first. And thus, it is "undefined behavior".

You seem to be implying that the behavior will definitely be that of one of the possible orderings, but that's not the case. It's just not unspecified, which increment happens first - the behavior is completely undefined. As far as the standard is concerned, the code may print "23 42" or even crash.

In fact gcc produces "4 5" as the output, which is neither consistent with a++ being evaluated first (that should produce "3 5"), nor with ++a evaluated first (that should produce "4 4").

So, for the most part, sequence points coincide with where you'd find semi-colons (;) in the code (with the exception of short-circuit operators like && and ||).

The comma operator and the conditional operator introduce sequence points as well. As do function calls (that is there is a sequence point between the evaluation of the arguments and the evaluation of the body - there is no sequence point between the function's arguments).

Speaking of function calls, I need to correct my earlier answer: The fact that the built-in << operator does not introduce a sequence point is irrelevant because here we're using an overloaded << operator and overloaded operators behave like function calls. This doesn't change that the behavior is undefined though since there is no sequence point between …

vijayan121 commented: Yes +14
sepp2k 378 Practically a Master Poster

As the error message says, input only expects a single argument (or none), but you give it three. The print function can take multiple arguments and will then just print one after the other (on the same line). The input function does not do that - you have to call it with a single string.

To create a single string for your prompt, you can use the format method like this:

action = input("Trade number {} (buy/sell)?".format(i))
Gribouillis commented: indeed +14
sepp2k 378 Practically a Master Poster

I'm not sure what you mean. If you want to put your member functions into your vector, you need to change the type of your vector (and then also change the calls when you call the functions). An example of this would be:

class CPerson
{
        public:
                CPerson(void) {};
                ~CPerson(void) {};
                typedef std::function<bool(CAle&, CPerson*, CPerson*)> FUNCTIONPOINTER;
                vector<FUNCTIONPOINTER> fp_Sip;
};

int main(void)
{
        // ...
        for (auto it = Person.fp_Sip.begin(); it != Person.fp_Sip.end(); ++it)
                (*it)(Ale, pP1, pP2);
        Person.fp_Sip.at(enSip3)(Ale, pP1, pP2);
}

If you don't want that, you need to bind the first argument using std::bind.

PS: Note that there's a lot of undefined behavior in your program as your bool functions don't actually return a value and you don't initialize your pointers.

PPS: The return value of main should be 0 - not 1 - when your application exits successfully.

sepp2k 378 Practically a Master Poster

Currently you have a regex that matches the whole string and then replace that with 'a'. So the whole string is going to be replaced with a single 'a'.

If all you want is to replace every character with one 'a' per character, just use a regex that matches a single character. If there are no special requirements on the characters, you can just do:

result = re.sub('.', 'a', 'Cat')

The count = 0 is unnecessary because that's the default.

sepp2k 378 Practically a Master Poster

You can also use for animal, noise in instead of for tpl in. Then you can use animal and noise instead of tpl[0] and tpl[1] respectively.

M.S. commented: thanks :) +4
sepp2k 378 Practically a Master Poster

It's valid, but it very likely won't do what the OP wants it to. You'll need parentheses around the arguments and the whole expression (though the latter doesn't matter in this case).

Or they could make their life 1000 times easier and define it as a function instead of a macro.

sepp2k 378 Practically a Master Poster

The construct template<typename T> is used to paramatrize classes, structs, unions, functions or, in C++ 11, type aliases with type parameters (or in some cases other compile-time parameters). So template<typename T> must be in front of the definitions of one of those things (like template<typename T> class Foo {...}). In your case it's inside a function body, which is not allowed.

It's not clear what you want parametrize here. If you wanted to parametrize main, you'd need to write template<typename T> int main(), except that it's not legal for main to be a template function because main is called by the operating system and the OS would not know which type to supply as an argument.

So you'd need to define your own function template<typename T> mymain(), put the code in there and then call that from main with the appropriate type argument. Except that won't work either because:

T one = "test";
T two = 255;
T three = 287.52;
T four = 'x';

Those four variables can't have the same type (unless there's a custom defined class with implicit constructors accepting each of the four types, but in your code there's not).

It's important to understand that in any given instantiation of a template, all occurrences of T refer to the same type. So if call, say mymain<int>() and mymain contains the above code, it will behave like you wrote:

int one = "test";
int two = 255;
int three = 287.52;
int four = …
sepp2k 378 Practically a Master Poster

If a function is nested in another function, you're not allowed to use unqualified exec in either of the two functions. Unqualified in this case means "without in". An explanation of why this limitation exists can be found here.

In your code you don't really need exec. To set and get global variables by name, you can just use globals()[name], but you don't even need global variables either. You can just define cache and rankings as local variables in mu_cache and then access them in wrap.

Another error in your code is that you use global rankings in delete_smallest. This will cause an error message about there being no global variable named rankings because rankings is a local variable in the wrap function, not a global variable. If you just remove that line, the error will disappear and you will be correctly able to access the rankings variable.

Gribouillis commented: very good remarks +14
sepp2k 378 Practically a Master Poster

Your code won't print all palindromes in all cases:

A palindrome can contain other palindromes that aren't its "inner strings". Take the string "kakykak" for example. Your algorithm will find "kakykak", "akyka" and "kyk", but not the two "kak"s.

Another problem is that palindromes can overlap. For example "akala" contains the palindromes "aka" and "ala", but your code wouldn't find the latter because after finding "aka", it would skip right to index 3 (the "l") and would not look for any palindromes starting at index 2.

Also technically every single letter of the string is a palindrome by itself, too.

As far as I can tell there is no more efficient way to do this

I'm assuming that the OP came across this problem in a programming contest or a site with a collection of algorithm problems or something of that sort (or possibly homework). And in those kinds of sites/contests, they wouldn't pose a problem that can't be solved in a reasonable amount of time (meaning O(n^2) at most usually). So for that reason alone I'd expect there to be a more efficient algorithm.

iamthwee commented: nice +14
sepp2k 378 Practically a Master Poster

It means if stdout is writing normally to the screen, it will automatically be flushed when you print a newline. But when it's writing to, say, a file or a pipe, the file won't be actually written to until the buffer is full, you explicitly flush it or the program ends.

sepp2k 378 Practically a Master Poster

When people talk about stdout being line-buffered, that means that if you do printf("Hello ");, then wait for some seconds and then printf("world!\n");, the output will appear all at once as "Hello world!" when the couple of seconds are over. If you used stderr instead (or you flushed stdout after the first printf), you'd see "Hello" right away and then a couple of seconds later the rest of the message would appear.

Since your format string ends with a \n anyway, that's not your problem at all. Even using stdout, your message will appear as soon as you print it, so using stderr instead changes nothing (except that it will mess with output redirection and such).

Your problem is that getchar won't return until the user entered a full line - i.e. it won't return right after the user entered the first character. That's not something you can change using only the functionality provided by the C standard. Depending on which platform you're targetting, there are platform-specific functions to do what you want though.

somjit{} commented: thanks :) +3
sepp2k 378 Practically a Master Poster

Have you tried to compile the code? That should give you a list of errors telling you some of the things wrong with that code.

sepp2k 378 Practically a Master Poster

"GOOD EVENING" is an array of characters. If you take any array or pointer and write p + i, you get a pointer pointing to the address that's i elements after the location that p points to. So in case of an array, arr + i (or i + arr - order doesn't matter) produces a pointer to the element of the array arr at index i.

So 2 + "GOOD EVENING" produces a pointer that points to the second O in GOOD. Adding 6 to that moves the pointer 6 further to the right, producing a pointer that points to the first N in EVENING - same as if you had written "GOOD EVENING" + 8. So you pass a pointer to that N to printf and printf then prints all characters starting at that pointer until the end of the string. So that's why you get NING.

sepp2k 378 Practically a Master Poster

~s.o.s~, I think you overlooked the fact that someboundmethod is never actually called in the james' code. d simply stores a reference to the method someboundmethod of the object returned by foo(). Since that method is bound to the object, the object will live at least as a long as the method is referred to.

sepp2k 378 Practically a Master Poster

You can't do cout << *(POINTER + 2) for the same reason that you can't do cout << *POINTER or cout << OBJECT: There is no overload for operator << that takes an ostream and a CLASS.

Also POINTER + 2 does not add two bytes to the pointer, it adds 2 * sizeof(CLASS) bytes to the pointer. Which of course will invoke undefined behavior since there's only one object in the memory that POINTER is pointing to, not three.

nmakes commented: OK. Now I got that + 2 thing. Thanks! +1
sepp2k 378 Practically a Master Poster
walls,corner[2] = (' #')

You accidentally typed a comma instead of a period here.

As a result the parser things you want to assign to a local variable called walls as well as to the second element of a variable named corner. Because of this Python now thinks that walls is a local variable and thus produces an error when you try to access it before its value has been set.

sepp2k 378 Practically a Master Poster

it's undefined because you have no idea what other functions will do with it.

Admittedly I just found out that it's undefined 45 minutes ago, but I'm pretty sure that's not the reason why. By that logic copying the pointer to a different variable or passing it to a function that we defined ourselves would not invoke UB because then we would know what's being done with it. But according to this (page 49, lines 14+) any use of an illegal pointer invokes UB.

Also we do know what printf does with its arguments. Since the standard does not mandate that the argument for %d shall be a pointer that's legal to dereference (which it doesn't, since the argument for %d shouldn't even be a pointer), any implementation that does dereference the argument would be in violation of the standard. Likewise the standard does not mandate that %p (which the OP should be using) dereferences its argument and therefore it won't. In particular it is legal to do printf("%p", arr+n) where arr is an array of size n. If printf could potentially dereference an argument for %p, that would not be legal.

As a sidenote, there's another reason why the code invokes undefined behavior: %d expects an integer, but is given a pointer.

sepp2k 378 Practically a Master Poster

By the way, you could also perform a XOR swap.

Neither pointers nor floats can be operands to ^, so neither of your macros will work with the OP's float pointers.

sepp2k 378 Practically a Master Poster

Earlier I tried this code on windows (IDE = visual studio), It was giving following errors:

The problem is that in C89 you're only allowed to declare variables at the beginning of a block. No further variable declarations are allowed after the first non-declaration in a given block.

So this would be legal:

int main() {
    int x = 7;
    int y = 8;
    return 0;
}

But this would not:

int main() {
    int x;
    x = 7;
    int y = 8;
    return 0;
}

Because here line 4 is a declaration, but line 3 isn't. If you put the declaration of y in a new block, it's legal again:

int main() {
    int x;
    x = 7;
    {
        int y = 8;
        return 0;
    }
}

So to fix your code sample, you can either initialize p and q on line 7 and remove lines 8 and 9, so that the declaration of t is still at the beginning of the block - or you could add braces around the body of your macro, so that it creates its own block.

The latter is much preferable because it allows you to use the macro in the middle of a block - not just at the beginning - and it limits the scope of the t variable, so that you can use SWAP multiple times in the same scope and even in a scope where there's already a variable named t

sepp2k 378 Practically a Master Poster

am i right 100% ?

Yes.

explain me why is it neccasary to fflush the streams ?

When I run your code without flushing or adding newlines, I get a different amount of output every time I run it.

To be honest I'm not sure why anymore. I wanted to say that forking while there's still output in the buffer, will give the forked process a copy of the buffer, leading to duplicated output. That's true, but your code only prints after forking, so that shouldn't be a problem here (also the problem is that I (sometimes) get too little output when I run your code - not too much).

sepp2k 378 Practically a Master Poster

but if i want to know without running it ?

Then you run it in your head.

First note that the return values of the first three forks do not matter - you assign each of them to ret, but then you overwrite them right afterwards without using them. So you can simplify the code by writing it as:

fork();
fork();
fork();
ret = fork();

Now if you understand the fundamentals of fork, you know that each fork creates a new process and the control flow in that process starts right after that call to fork. So after the first fork you have two processes and each of them will then execute the second call to fork. Both of those calls will create another process. So you now have two new processes, making a total of four. Now those four processes all execute the third fork and so on...

sepp2k 378 Practically a Master Poster

I do agree with Tokamak that the c++ example he mentioned is closer to how my intuition expects the code to work than Java.

You and Tokamak are certainly not the only people whose intuition goes that way (mostly, I think, because a lot of people mis-explain x++ as "do something with x and then increment x afterwards") and I do agree that some people's reactions here were needlessly arrogant for something that really a lot of people do get wrong. That said it's still wrong and based on a misunderstanding of how x++ works.

If ++ was a method, and num an object, the num = num++; would have behaved the way Tokamak and I would expect it to.

Definitely not. Consider this class:

class MyInt {
    private int value;
    public MyInt(int value) {
        this.value = value;
    }

    public MyInt postInc() {
        int oldValue = value;
        value = value + 1;
        return new MyInt(oldValue);
    }
}

This definition of postInc will behave exactly like ++ behaves for primitive ints. More importantly: there is no way to change the defintion of postInc so that it would behave the way you expect/want it to.

---

Another thing: I know I'm repeating myself, but several people in this thread have now referred to "the way that it works in C++" and I just want to reiterate that there is no way in which it works in C++. A C++ application in which you use this construct …