Translate

nnn

ads

Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

1 Aug 2019

Is it fine to jot down “void main()” or “main()” in C/C++?

Is it fine to jot down “void main()” or “main()” in C/C++?


c



Is it fine to jot down “void main()” or “main()” in C/C++?

wordpress



is not and ne'er has been C++, nor has it even been C. See the ISO C++ commonplace 3.6.1[2] or the ISO C commonplace 5.1.2.2.1. A conforming implementation accepts




html


and


css



A conforming implementation might give a lot of versions of main(), however they have to all have come back type int. The int returned by main() could be a method for a program to come back a value to “the system” that invokes it. On systems that doesn’t give such a facility the come back value is neglected, however that doesn’t build “void main()” legal C++ or legal C. even if your compiler accepts “void main()” avoid it, or risk being thought-about ignorant by C and C++ programmers.
In C++, main() needn't contain a certain come back statement. in this case, the value came back is 0, which means productive execution.


example:


javascript

Note also that neither ISO C++ nor C99 permits you to go away the kind out of a declaration. That is, in distinction to C89 and ARM C++ ,”int” isn't assumed wherever a type is missing in an exceedingly declaration. Consequently


book


31 Jul 2019

int (1 sign bit + 31 data bits) in C


int (1 sign bit + 31 data bits)  in C
Book



In C programing language a commonest keyword ‘int’ is employed to outline any positive or negative number. however there's a distinction between an integer and also the numbers which may be depicted with the assistance of the keyword ‘int’. Not each integer will be depicted with the keyword ‘int’. in keeping with MinGW the scale of 1 ‘int’ is 4 bytes that is adequate 32 bits (1 byte=8 bits). it's still a story somewhere that ‘int’ will represent an integer or ‘int’ is employed to represent integers. number could be a terribly huge class of numbers wherever joined ‘int’ has restricted and actual quantity of memory (size of ‘int’ is 4 bytes or 32 bits) to store what's being depicted by it. an ‘int’ sort variable in C language is ready to store solely numbers until 2147483647. on the far side this variety ‘int’ fails to store exactly and even not properly. ‘int’ could be a 32 bit knowledge sort. Whenever variety is being assigned to an ‘int’ sort variable, it's initial converted to its binary illustration (that is in 0’s and 1’s) then it's unbroken in memory at specific location. associate degree ‘int’ is really one sign bit + 31 data bits, that's thirty one bits are accessible for storing the quantity being appointed to a ‘int’ sort variable and one bit is reserved for maintaining the sign of the quantity that is either + or – . The sign is additionally depicted by binary digits, 0 for positive sign and 1 for negative sign


Example – Consider

C



At now 1st 2147483647 are regenerate into its binary kind that is equal to:

1111111111111111111111111111111.

1111111111111111111111111111111 could be a 31 digit binary number can|which can|which could be able to} be assigned to variable num’s right most 31 bits and also the 32nd bit will have a zero(0) because the number being assigned to variable num is a positive variety. If we Associate in Nursingd} store any variety larger than 2147483647 into an ‘int’ sort variable then we are going to lose data.




27 Jun 2019

Signals in C language


Signals in C language




Prerequisite : Fork system call, Wait call
A signal could be a software package generated interrupt that's sent to a process by the OS attributable to once user press ctrl-c or another method tell one thing to the present method.
There area unit fix set of signals which will be sent to a method. signal area unit known by integers.
Signal variety have symbolic names. as an example SIGCHLD is variety of the signal sent to the parent method once kid terminates.
Examples:



#define SIGHUP  1   /* Hangup the process */
#define SIGINT  2   /* Interrupt the process */
#define SIGQUIT 3   /* Quit the process */
#define SIGILL  4   /* Illegal instruction. */
#define SIGTRAP 5   /* Trace trap. */
#define SIGABRT 6   /* Abort. */




  ü OS Structures for Signals

For each method, the operating system maintains two integers with the bits resembling a signal numbers.
The two integers keep track of: unfinished signals and blocked signals




Example : 

In the example below, the intelligence operation ( = 2) signal is blocked and no signals are unfinished.

Pending Signals :

   31         30      29         28      ......       3           2          1           0
0
0
0
0
……
0
0
0
0


Blocked Signals :

    31         30      29         28      ......       3           2          1           0
0
0
0
0
……
0
0
0
0


A signal is distributed to a process setting the corresponding bit within the unfinished signals number for the process. anytime the OS selects a method to be run on a processor, the unfinished and blocked integers ar checked. If no signals ar unfinished, the method is restarted commonly and continues death penalty at its next instruction.


If 1 or additional signals ar unfinished, however all is blocked, the method is also restarted commonly however with the signals still marked as unfinished. If one or additional signals ar unfinished and NOT blocked, the OS executes the routines within the process’s code to handle the signals.

Default Signal Handlers

There are many default signal handler routines. every signal is related to one amongst these default handler routine. the various default handler routines generally have one amongst the subsequent actions:

  Ø  Ign: Ignore the signal; i.e., do nothing, simply come back
  Ø  Term: terminate the method
  Ø  Cont: unblock a stopped method
  Ø  Stop: block the method



// CPP program to illustrate 
// default Signal Handler 
#include<stdio.h> 
#include<signal.h> 

int main() 

signal(SIGINT, handle_sigint); 
while (1) 

printf(“hello world\n”); 
sleep(1); 

return 0; 



Output: Print hello world infinite times. If user presses ctrl-c to terminate the process because of SIGINT signal sent and its default handler to terminate the process.


hello world
hello world
hello world

terminated

User outlined Signal Handlers

A method will replace the default signal handler for nearly all signals (but not SIGKILL) by its user’s own handler perform.
A signal handler perform will have any name, however should have return sort void and have one int parameter.
Example: you would possibly opt for the name sigchld_handler for a signal handler for the SIGCHLD signal (termination of a toddler process). Then the declaration would be:




void sigchld_handler(int sig);




When a symbol handler executes, the parameter passed to that is that the range of the signal. A applied scientist will use identical signal handler operate to handle many signals. during this case the handler would wish to ascertain the parameter to examine that signal was sent. On the opposite hand, if a symbol handler function solely handles one signal, it isn’t necessary to hassle examining the parameter since it'll continuously be that signal number.

// CPP program to illustrate 
// User-defined Signal Handler 
#include<stdio.h> 
#include<signal.h> 

// Handler for SIGINT, caused by 
// Ctrl-C at keyboard 
void handle_sigint(int sig) 

printf("Caught signal %d\n", sig); 


int main() 

signal(SIGINT, handle_sigint); 
while (1) ; 
return 0; 




^CCaught signal 2  // when user presses ctrl-c
^CCaught signal 2

Sending signals via kill()
We can send a signal using kill() to the process

int kill(pid_t pid, int signal);
pid: id of destination process
signal: the type of signal to send

Return value: 0 if signal was sent successfully

Example :

pid_t iPid = getpid(); /* Process gets its id.*/
kill(iPid, SIGINT);  /* Process sends itself a  SIGINT signal  
(commits suicide?)(because of SIGINT
signal default handler is terminate the process) */
        

1. What is the Output of the following program?

#include<stdio.h>
#include<wait.h>
#include<signal.h>
int main()
{
            int stat;
            pid_t pid;
            if ((pid = fork()) == 0)
                        while(1) ;
            else
            {
                        kill(pid, SIGINT);
                        wait(&stat);
                        if (WIFSIGNALED(stat))
                                    psignal(WTERMSIG(stat), "Child term due to");
            }
}


Output:

 Child term due to: Interrupt

2. What is the Output of the following program?

#include<stdio.h>
#include<signal.h>
#include<wait.h>
int val = 10;
void handler(int sig)
{
val += 5;
}
int main()
{
pid_t pid;
signal(SIGCHLD, handler);
if ((pid = fork()) == 0)
{
val -= 3;
exit(0);
}
waitpid(pid, NULL, 0);
printf("val = %d\n", val);
exit(0);

}



val = 15


3. Consider the following code. What is the output?

void handler2(int sig) 
counter += 3; 
printf("counter = %d\n", counter); 
exit(0); 

int main() 
pid_t p; 
int status; 
signal(SIGUSR1, handler1); 
if ((pid = fork()) == 0) 
signal(SIGUSR1, handler2); 
kill(getppid(), SIGUSR1); 
while(1) ; 
if ((p = wait(&status)) > 0) 
counter += 4; 
printf("counter = %d\n", counter); 

Output

counter = 1         //(parent’s handler)
counter = 3         //(child’s handler)
counter = 5         //(parent’s main)

Difference between while(1) and while(0) in C language

Difference between while(1) and while(0) in C language



In most programing languages, a jiffy loop may be a control flow statement that enables code to be executed repeatedly supported a given mathematician condition. The mathematician condition is either true or false

while(1)

It is Associate in Nursing infinite loop which can run until a prospect statement is issued expressly. apparently not while(1) however any number that is non-zero can provide the similar result as while(1). Therefore, while(1), while(2) or while(-255), all can provide infinite loop only.

while(1) or while(any non-zero integer)
    // loop runs infinitely
}


A simple usage of while(1) will be within the Client-Server program. within the program, the server runs in an infinite whereas loop to receive the packets sent type the purchasers.But much, it's not advisable to use while(1) in realworld as a result of it will increase the computer hardware usage and additionally blocks the code i.e one cannot start from the while(1) till the program is closed manually.while(1) will be used at an area wherever condition has to be true continually

while(1) is used at an area wherever condition must be true always

// C program to illustrate while(1) 
int main() 
int i = 0; 
while ( 1 ) 
printf( "%d\n", ++i ); 
if (i == 5)  
break; // Used to come 
// out of loop 
return 0; 

1
2
3
4
5

while(0)

It is opposite of while(1). It suggests that condition can perpetually be false and therefore code in whereas can never get executed.

while(0)
{
    // loop does not run
}


// C program to illustrate while(0) 
int main() 
int i = 0, flag=0; 
while ( 0 ) 
// This line will never get executed 
printf( "%d\n", ++i ); 
flag++; 
if (i == 5) 
break; 
if (flag==0) 
printf ("Didn't execute the loop!"); 
return 0; 


Output:

Didn't execute the loop!


C programming language commonplace


C programming language commonplace



The idea of this text is to introduce C commonplace.What to try and do once a program produces different|completely different} results in 2 different compilers?
For example, consider the subsequent easy program.


void main()

The above program fails in sayed 360 because the come style of main is void, however it compiles in Turbo C. however will we decide whether or not it's a legitimate c program or not?

Consider the subsequent program as another example. It produces completely different|completely different} results in different compilers.



#include<stdio.h> 
int main() 

int i = 1; 
printf("%d %d %d\n", i++, i++, i); 
return 0; 



2 1 3 - using g++ 4.2.1 on Linux.i686
1 2 3 - using SunStudio C++ 5.9 on Linux.i686
2 1 3 - using g++ 4.2.1 on SunOS.x86pc
1 2 3 - using SunStudio C++ 5.9 on SunOS.x86pc
1 2 3 - using g++ 4.2.1 on SunOS.sun4u
1 2 3 - using SunStudio C++ 5.9 on SunOS.sun4u
  


  Ø What is C standard?
The latest C standard is ISO/IEC 9899:2011, conjointly referred to as C11 because the final draft was revealed in 2011. Before C11, there was C99. The C11 final draft is offered here. See this for complete history of C standards.


  Ø  Can we all know behavior of all programs from C standard?

C standard leaves some behavior of the many C constructs as undefined and a few as some to modify the specification and permit some flexibility in implementation. for instance, in C the use of any automatic variable before it's been initialized yields undefined behavior and order of evaluations of sub expressions is some. This specifically frees the compiler to try and do no matter is best or most effective, ought to such a program be submitted.


  Ø  So what's the conclusion regarding higher than two examples?

Let us contemplate the primary example that is “void main() ”, the quality says following regarding example of main()



The function called at program startup is named main. The implementation
declares no prototype for this function. It shall be defined with a return
type of int and with no parameters:
       int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names
may be used, as they are local to the function in which they are declared):
       int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.





So the return type void doesn’t follow the quality and it’s one thing allowed by bound compilers.Let us mention second example. Note the subsequent statement in C standard is listed below unspecified behavior.



The order in which the function designator, arguments, and
subexpressions within the arguments are evaluated in a function
call (6.5.2.2).







  Ø  What to try and do with programs whose behavior is       indefinable or unspecified in standard?

As a programmer, it's ne'er a decent plan to use programming constructs whose behaviour is indefinable or unspecified , such programs should be discouraged. The output of such programs might modification with compiler and/or machine