How to make my program(exe) to stop(and not exit) once an event(generation of a text file) has occured? - visual-studio-2010

I am creating an executable in visual studio.
My code goes like this:
if(condition)
goto Step 1
else
goto Step 2
Step 1:
code
Step 2:
code
I want to make this in a way that if Step 1 has run then Step 2 must be skipped.
Should it be done using functions?

Within your class It can be placed in two functions and called from the if - else logic or you can place the code in between the if and else. If the code is large then it would be better to create two functions.
If (condition)
call function step1
else
call function step2
or
if (condition)
code...
else
code...
C# Example of defining a method and calling it:
public void Caller()
{
int numA = 4;
// Call with an int variable.
int productA = Square(numA);
int numB = 32;
// Call with another int variable.
int productB = Square(numB);
// Call with an integer literal.
int productC = Square(12);
// Call with an expression that evaulates to int.
productC = Square(productA * 3);
}
int Square(int i)
{
// Store input argument in a local variable.
int input = i;
return input * input;
}

Related

Invalid use of int and no static main entry

It says there is no suitable entry point for the program as well as invalid expression of int when attempting to use the printMenu method. My instructions specify that I need to initialize the array and menu in the main and utilize the 5 methods in a switch statement but I am tripping over the Main method. I am unable to understand how to reference an (int[] args) with a string. I was able to do it just fine with a switch statement but since moving onto methods I have struggled understanding how to reference properly and would appreciate any tops or fixes on how to adjust.
public static void Main(string[] args)
{
int[] initArray = new int[10];
Console.Write("Would you like to: \n1) Enter a number\n2)Print the array \n3)find the sum of the array\n4)Reset the array\n5)Quit\n");
int input = Convert.ToInt32(Console.ReadLine());
printMenu(int[input]);
}
public void printMenu(int[] args)
{
Console.Write("Would you like to: \n1) Enter a number\n2)Print the array \n3)find the sum of the array\n4)Reset the array\n5)Quit\n");
int input = Convert.ToInt32(Console.ReadLine());
do
{
switch (input)
{
case 1:
enterNum(args);
break;
}
} while (input < 5);
}
You can call the printMenu method like this:
printMenu(new int[]{ input });
If you have a second input you would do:
printMenu(new int[]{ input, input2 });
Using an array of integers is only logical when you want to pass in multiple integers. When you are never going to pass in more than 1 ints I suggest changing the signature of printMenu to ask for just one integer: printMenu(int arg) and just pass in the one input.
printMenu(input);

MPI: How to ensure a subroutine is executed only on one processor on the default node?

I use a large-scale parallelized code, and I am new to MPI itself.
I try to run a set of shell commands from Fortran, and hence it would be entirely wasteful (and cause my results to be incorrect) if done on more than one processor.
The most relevant commands I have found are MPI_gather and MPI_reduce, but these seem problematic, because they are trying to take information from other processors and use them on the processor 0, but I have no information that I am calling from other processors.
Basically I want to do something like this :
if (MPI_node = 0 .and. MPI_process = 0) then
(execute a code)
end if
I recently had an issue like this. The way I solved it was to use MPI_Comm_split to create a communicator for each node. Something like this (C++):
char node_name[MPI_MAX_PROCESSOR_NAME];
int name_len;
int processor_hash_id;
int global_proc_id;
int global_proc_num;
int node_proc_id;
int node_proc_num;
MPI_Comm node_comm;
//Get global info
MPI_Comm_rank(MPI_COMM_WORLD, &global_proc_id);
MPI_Comm_size(MPI_COMM_WORLD, &global_proc_num);
MPI_Get_processor_name(node_name, &name_len);
//Hash the node name
processor_hash_id = get_hash_id(node_name);
//Make a new communicator for processes only on the node
// and get node info
MPI_Comm_split(MPI_COMM_WORLD, processor_hash_id, global_proc_id, &node_comm);
MPI_Comm_rank(node_comm, &node_proc_id);
MPI_Comm_size(node_comm, &node_proc_num);
//Now, if you know the name of the "root node" to execute shell commands on:
if (node_proc_id==0 && processor_hash_id == get_hash_id("name-of-root-node"))
{
//do whatever
}
//Some hash function
int get_hash_id(const char* s)
{
int h = 37;
while (*s)
{
h = (h * 54059) ^ (s[0] * 76963);
s++;
}
return h;
}
Of course you will need to know the name of the root node.
If it doesn't matter what node it executes on, then I would suggest the following:
int global_proc_id;
int global_proc_num;
//Get global info
MPI_Comm_rank(MPI_COMM_WORLD, &global_proc_id);
MPI_Comm_size(MPI_COMM_WORLD, &global_proc_num);
if (global_proc_id==0)
{
//do whatever
}
global_proc_id==0 will only be true on one node.

replace existing object on the stack with default constructed one

I would like to know the best/correct way to get back to the initial values of an object without playing with delete and new (everything must stay on the stack)
With this 2 classes:
static const int defaultValue{15};
class Foo
{
private:
int val1{defaultValue};
short val2{4};
}
class LongStandingObject
{
public:
void resetFoo(int index);
private:
Foo foos[100];
}
If I need to reset some foos to their default values, what is the best way?
Create reset method in Foo
void Foo::reset()
{
val1 = defaultValue;
val2 = 4;
}
I don't really like the idea to have the values coming from 2 differents places and I do like to have the defaults values in the header next to the variable declaration.
Replace by a locally created Foo
void LongStandingObject::resetFoo(int index)
{
foos[index] = Foo();
}
Am I heading to trouble when the local variable is destroyed?
Use memcpy
void LongStandingObject::resetFoo(int index)
{
Foo foo;
memcpy(foos[index], &foo, sizeof(Foo));
}
Maybe less readable...
Any other method?
Your #2 is just fine, and probably the most legible.
void LongStandingObject::resetFoo(int index)
{
foos[index] = Foo();
}
There are no object lifetime issues here: the assignment operator is called on foos[index] to change its values to match the temporary object materialized from Foo(). That is, the code is exactly equivalent to
{
Foo tmp;
foos[index].val1 = tmp.val1;
foos[index].val2 = tmp.val2;
}
And if optimizations are enabled, almost any compiler will be able to just modify foos[index] directly without actually creating the temporary Foo.
If you do want a Foo::reset() function as well, you can use the same idea for it:
void Foo::reset()
{
*this = Foo();
}
I would avoid using memcpy, since the program would become incorrect if you ever make changes to Foo that make it no longer trivially copyable.
What you can do is to use std::pair on each variable. Initialized with with variable.first = variable.second = value. After, every time you want to update the variable you set: variable.second = new_value. When you want to restore to the original, you set: variable.second = variable.first. You can improve it by writing a macro RestoreDefault(var) to make the code more readable.
For example:
#define RestoreDefault(var) ((var).second = (var).first)
// int val1{180}; // Instead of this line
std::pair<int,int> val1{ 180,180}; // <- this line
val1.second = 456;
RestoreDefault(val1);
If you want to hardcoded block any possibility to re-set later the default value, write:
std::pair<const int,int> val1{ 180,180}; // <- this line
-
Addition: Same principle for array:
class Foo
{
public:
int x = 100;
int y = 200;
};
#define RestoreArrDefault(var) ((var).second.fill((var).first))
// Use:
std::pair<Foo, std::array<Foo, 100>> FooAr, FooAr2;
// You can define different arrays with different defaults:
FooAr.first = { 180,360 }; // <- Customize FooAr defaults
// In that point FooAr default is 180,360 and FooAr2 default is 100,200
FooAr.second[3] = { 2,10 }; // <- Edit FooAr index-3 item
RestoreArrDefault(FooAr); // <- Restore Default

Memory allocation of string literal in c

I am having a strange issue with memory allocation in c, the file is fairly complicated so I cannot include it all here but perhaps you can point me in the right direction as to why this may be happening.
I am trying to create a string literal as such:
char * p = "root"
But when i look at the value of this variable at runtime (at the line directly after the declaration) i get this:
$1 = 0x7001260c "me"
and when I look at the contents of the memory at 0x7001260c it indeed holds the string "me".
EDIT:
To give more context when I run the following code the value of p on the last line is "root".
create_directory("root/home");
char * p = "root";
char * q = "foo";
And when I run the following code the value of p is "io"
create_directory("io/home");
char * p = "root";
char * q = "foo";
The create_directory function:
void create_directory(char * path) {
directory d;
directory * dir = &d;
//Browse to closest directory
path = find_directory(path, dir);
//Create remaining directories
char component[20];
path = next_component(path, component);
while (strlen(component) > 0) {
add_dir_entry(dir, component, inode_next);
write_dir_entry(dir, inode_to_loc(dir->inode));
directory new;
new.type = DIRECTORY;
new.inode = inode_next;
write_dir_entry(&new, inode_to_loc(inode_next));
inode_next++;
dir = &new;
path = next_component(path, component);
}
}
Almost certainly, there's a bug somewhere in your program that causes a constant to be modified which is, of course, illegal. Perhaps you're doing something like this:
void to_lower(char *j)
{
while (*j != 0) { *j = tolower(*j); j++; }
}
...
bool is_yes(char *k)
{
to_lower(k);
return strcmp(k, "yes") == 0;
}
void someFunc(char *k)
{
if (is_yes(k)) // ...
...
}
someFunc("testing");
See what this does? We pass a pointer to a constant to sumeFunc, but it flows down to to_lower which modifies the thing it points to -- modifying a constant.
Somehow, your code probably does something like that.
Start by changing code like char * p = "root" to code like char const* p = "root". That will give you a better chance of catching this kind of problem at compile time.

Why is a temporary variable required in foreach to be included in lambda expression?

I was reading C# 4 in a Nutshell and I've come to this piece of code:
IQueryable<Product> SearchProducts (params string[] keywords)
{
IQueryable<Product> query = dataContext.Products;
foreach (string keyword in keywords)
{
string temp = keyword;
query = query.Where (p => p.Description.Contains (temp));
}
return query;
}
Right after the code there's a 'warning' that goes like this:
The temporary variable in the loop is required to avoid the outer variable trap, where the same variable is captured for each iteration of the foreach loop.
I don't get it, I don't understand why the temp variable is necessary. What is the outter variable trap?
From: http://www.albahari.com/nutshell/predicatebuilder.aspx
Can anybody please clarify this?
Because there is only one variable called keyword that is closed over. The temporary variable, however, is different each iteration.
Thus, without the temporary variable, when the lambda is executed later, keyword evaluates to the last value it was assigned in the loop.
Another solution, in some cases, is to force the evaluation (and end up with a List or such).
The problem is that keyword is changing. The => delegate closes on the current value of the variable, not the value it had back in the past when the delegate was created. There's a detailed explanation in Eric Lippert's blog post.
This classic C bug is the same mistake:
#include <stdio.h>
#include <pthread.h>
void * MyThreadFunction(void *x)
{
printf("I am thread %d\n", * (int *) x);
return NULL;
}
int main(void)
{
int i;
pthread_t t[10];
void *ret;
for(i=0; i<10; i++)
pthread_create(&t[i], NULL, MyThreadFunction, (void *) &i);
for(i=0; i<10; i++)
pthread_join(t[i], &ret);
}
The * (int *) x gets the current value of i, not the value when the thread was created.

Resources