The goto Statement in C ?

By Shakib Ansari | Date: Sat, May 3, 2025

Hamne ab tak bahut saare tareeke discuss kare hai ko ki flow of execution ko control karte hai based on some conditions. Other languages ki tarah hi, C language bhi goto statement ko support karti hai 'unconditionally' from one point to another in the program. Although C language jo ki highly structured language hai us mein goto statements zyada essential nhi hoti, kuch hi situations par ham goto statements ka use karte hai.

The goto ke liye hame label require hota hai jo identify karte hain ki hame kaha flow of execution le jana hai. Ek label koi valid variable name ho sakta hai, aur label ke baad colon lagana zaruri hota hai. Label ko ham immediately before the statement place karte hai jaha hame program ke flow ko transfer karna hota hai.

The label: kahi bhi place ho sakta hai ya to before ya after the goto label; statement.

Suppose karo ek program ki statement kuch is tarah likhi hai. goto begin;

jab ye statement run hogi to flow of control immedieately label begin par jump kar jayega... Ye unconditionally hoga. goto statement normal sequential execution ko break kar deta hai. Agar label; pehle hai goto label se, to yaha par ek loop formed ho jaygi aur kuch statements repeatedly execute hongi. Aisi jump ko backword jump bhi kehte hai. On the other hand, agar label; goto label ke baad place hai to kuch statements skipped ho jayengi aur ise forword jump kehte hai.

A goto normally end of the program mein use hoti hai jisse ham direct kar de control ko input statement par, jisse new data read kar sakte hai. Consider the following example:

#include<stdio.h>
#include<math.h>
int main()
{
    double x, y;
read: // label:
    scanf("%lf", &x);
    if (x < 0)
        goto read; 
    y = sqrt(x);
    printf("%f %f", x, y);
    goto read; // goto label;
}

Explanation: Is program mein ek series of numbers read honge from the terminal and square root ko evaluate karega. The program uses two goto statements. Ek end mein, result ko print karke aur control ko input par transfer back karne ke liye aur dusra computation ko skip kar dena jab input negative number ho. End wali unconditional goto statement ki wajah se, the control always transfer back kar dega input statement par. In fact is program mein permanent loop hai jise infinite loop bhi kehte hai. Ye program jab tak chalega jab tak ham kuch special steps na le like %ctrl+ c (for VS Code).

About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments